【通信协议及编码】实验2:三种I/O模型回送服务器程序设计

本文主要是介绍【通信协议及编码】实验2:三种I/O模型回送服务器程序设计,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

文章目录

  • 一、实验目的
  • 二、实验环境
  • 三、实验内容
    • 1.Select I/O服务器
    • 2.WSAEventSelect服务器
    • 3.I/O Completion Port


一、实验目的

  1. 掌握WinSock API I/O模型框架与原理
  2. 掌握WinSock API Select I/O模型;
  3. 掌握WinSock API WSAEventSelect I/O模型;
  4. 掌握WinSock API I/O Completion Port模型。

二、实验环境

  1. 操作系统:WINDOWS 7及以上
  2. 开发工具:Microsoft VisualBasic6.0
  3. 实验设备:PC

三、实验内容

  1. 基于Select I/O模型创建一个回送服务器,服务器在5150端口上侦听TCP连接,并将收到的客户机数据回送客户机。
  2. 设计一个WSAEventSelect I/O模型,服务器在端口5150侦听TCP连接,回送到客户机数据。
  3. 开发一个简单的WinSock回声服务器,应用程序监听端口5150的TCP连接,并将收到的客户机数据回送给客户机。

客户机:

//程序说明:
//    这是一个回送客户机程序。连接TCP server,发送数据,接收服务器回送的数据
//    命令行参数:
//    client [-p:x] [-s:IP] [-n:x] [-o]
//           -p:x      远程服务器端口
//           -s:IP     服务器地址或主机名
//           -n:x      消息的发送次数
//           -o        只发送,不接收 
#include "stdafx.h"
#include <winsock2.h>
#include <stdio.h>
#include <stdlib.h>
#pragma comment(lib,"ws2_32.lib")#define DEFAULT_COUNT       20
#define DEFAULT_PORT        5050
#define DEFAULT_BUFFER      2048
#define DEFAULT_MESSAGE     "\'A test message from client\'"char  szServer[128],          // 服务器主机名或地址
szMessage[1024];        // 发送到服务器的消息缓冲区
int   iPort = DEFAULT_PORT;  // 服务器端口
DWORD dwCount = DEFAULT_COUNT; // 发送消息的次数
BOOL  bSendOnly = FALSE;         // 只发送,不接收// 函数用法说明
void usage()
{printf("TcpClient: client [-p:x] [-s:IP] [-n:x] [-o]\n\n");printf("       -p:x      Remote port to send to\n");printf("       -s:IP     Server's IP address or hostname\n");printf("       -n:x      Number of times to send message\n");printf("       -o        Send messages only; don't receive\n");printf("\n");
}// 命令行参数解析
void ValidateArgs(int argc, char **argv)
{int	i;for (i = 1; i < argc; i++){if ((argv[i][0] == '-') || (argv[i][0] == '/')){switch (tolower(argv[i][1])){case 'p':if (strlen(argv[i]) > 3)iPort = atoi(&argv[i][3]);break;case 's':if (strlen(argv[i]) > 3)strcpy_s(szServer, sizeof(szServer), &argv[i][3]);break;case 'n': if (strlen(argv[i]) > 3)dwCount = atol(&argv[i][3]);break;case 'o':bSendOnly = TRUE;break;default:usage();break;}}}
}//    主线程初始化 Winsock, 分析命令行参数, 创建套接字, 连接服务器,发送和接受数据
int main(int argc, char **argv)
{WSADATA       wsd;SOCKET        sClient;char          szBuffer[DEFAULT_BUFFER];int           ret,i;struct sockaddr_in server;struct hostent    *host = NULL;if (argc < 2){usage();exit(1);}// 分析命令行参数,加载WinsockValidateArgs(argc, argv);if (WSAStartup(MAKEWORD(2, 2), &wsd) != 0){printf("Failed to load Winsock library! Error %d\n", WSAGetLastError());return 1;}elseprintf("Winsock library loaded successfully!\n");strcpy_s(szMessage, sizeof(szMessage), DEFAULT_MESSAGE);// 创建套接字,连接服务器sClient = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);if (sClient == INVALID_SOCKET){printf("socket() failed with error code %d\n", WSAGetLastError());return 1;}elseprintf("socket() looks fine!\n");server.sin_family = AF_INET;server.sin_port = htons(iPort);server.sin_addr.s_addr = inet_addr(szServer);if (server.sin_addr.s_addr == INADDR_NONE){host = gethostbyname(szServer);if (host == NULL){printf("Unable to resolve server %s\n", szServer);return 1;}elseprintf("The hostname resolved successfully!\n");CopyMemory(&server.sin_addr, host->h_addr_list[0], host->h_length);}if (connect(sClient, (struct sockaddr *)&server, sizeof(server)) == SOCKET_ERROR){printf("connect() failed with error code %d\n", WSAGetLastError());return 1;}elseprintf("connect() is pretty damn fine!\n");// 发送和接收数据printf("Sending and receiving data if any...\n");for (i = 0; i < (int)dwCount; i++){ret = send(sClient, szMessage, strlen(szMessage), 0);if (ret == 0)break;else if (ret == SOCKET_ERROR){printf("send() failed with error code %d\n", WSAGetLastError());break;}printf("send() should be fine. Send %d bytes\n", ret);if (!bSendOnly){ret = recv(sClient, szBuffer, DEFAULT_BUFFER, 0);if (ret == 0)        // 正常关闭{printf("It is a graceful close!\n");break;}else if (ret == SOCKET_ERROR){printf("recv() failed with error code %d\n", WSAGetLastError());break;}szBuffer[ret] = '\0';printf("recv() is OK. Received %d bytes: %s\n", ret, szBuffer);}}if (closesocket(sClient) == 0)printf("closesocket() is OK!\n");elseprintf("closesocket() failed with error code %d\n", WSAGetLastError());if (WSACleanup() == 0)printf("WSACleanup() is fine!\n");elseprintf("WSACleanup() failed with error code %d\n", WSAGetLastError());return 0;
}

1.Select I/O服务器

// 程序说明:
//
//    本程序演示如何基于Winsock 的 select() API I/O 模型创建一个回送服务器。
//    服务器在5150端口上侦听TCP连接
//    将收到的客户机数据再回送客户机,直到可会关闭连接#include <winsock2.h>
#include <windows.h>
#include <stdio.h>#pragma comment(lib,"ws2_32.lib")#define PORT 5150
#define DATA_BUFSIZE 8192typedef struct _SOCKET_INFORMATION {CHAR Buffer[DATA_BUFSIZE];WSABUF DataBuf;SOCKET Socket;OVERLAPPED Overlapped;DWORD BytesSEND;DWORD BytesRECV;
} SOCKET_INFORMATION, *LPSOCKET_INFORMATION;// 原型
BOOL CreateSocketInformation(SOCKET s);
void FreeSocketInformation(DWORD Index);// 全局变量
DWORD TotalSockets = 0;
LPSOCKET_INFORMATION SocketArray[FD_SETSIZE];int main(int argc, char **argv)
{SOCKET ListenSocket;SOCKET AcceptSocket;SOCKADDR_IN InternetAddr;WSADATA wsaData;INT Ret;FD_SET WriteSet;FD_SET ReadSet;DWORD i;DWORD Total;ULONG NonBlock;DWORD Flags;DWORD SendBytes;DWORD RecvBytes;if ((Ret = WSAStartup(0x0202, &wsaData)) != 0){printf("WSAStartup() failed with error %d\n", Ret);WSACleanup();return 1;}elseprintf("WSAStartup() is fine!\n");// 创建用于侦听的套接字if ((ListenSocket = WSASocket(AF_INET, SOCK_STREAM, 0, NULL, 0,WSA_FLAG_OVERLAPPED)) == INVALID_SOCKET){printf("WSASocket() failed with error %d\n", WSAGetLastError());return 1;}elseprintf("WSASocket() is OK!\n");InternetAddr.sin_family = AF_INET;InternetAddr.sin_addr.s_addr = htonl(INADDR_ANY);InternetAddr.sin_port = htons(PORT);if (bind(ListenSocket, (PSOCKADDR)&InternetAddr, sizeof(InternetAddr)) == SOCKET_ERROR){printf("bind() failed with error %d\n", WSAGetLastError());return 1;}elseprintf("bind() is OK!\n");if (listen(ListenSocket, 5)){printf("listen() failed with error %d\n", WSAGetLastError());return 1;}elseprintf("listen() is OK!\n");// 将侦听套接字的阻塞模式转为非阻塞模式,这样服务器在等待连接到达期间不会发生阻塞NonBlock = 1;if (ioctlsocket(ListenSocket, FIONBIO, &NonBlock) == SOCKET_ERROR){printf("ioctlsocket() failed with error %d\n", WSAGetLastError());return 1;}elseprintf("ioctlsocket() is OK!\n");while (TRUE){// 初始化等待网络I/O事件通知的读写套接字集合FD_ZERO(&ReadSet);FD_ZERO(&WriteSet);// 将侦听套接字加入套接字读集合FD_SET(ListenSocket, &ReadSet);// 基于当前状态缓冲区为每个套接字设置读/写// 如果缓冲区中有数据将其写入集合,否则读集for (i = 0; i < TotalSockets; i++)if (SocketArray[i]->BytesRECV > SocketArray[i]->BytesSEND)FD_SET(SocketArray[i]->Socket, &WriteSet);elseFD_SET(SocketArray[i]->Socket, &ReadSet);if ((Total = select(0, &ReadSet, &WriteSet, NULL, NULL)) == SOCKET_ERROR){printf("select() returned with error %d\n", WSAGetLastError());return 1;}elseprintf("select() is OK!\n");// 检查到达的连接在侦听套接字if (FD_ISSET(ListenSocket, &ReadSet)){Total--;if ((AcceptSocket = accept(ListenSocket, NULL, NULL)) != INVALID_SOCKET){// 设置套接字AcceptSocket为非阻塞模式// 这样服务器在调用WSASends发送数据时就不会被阻塞NonBlock = 1;if (ioctlsocket(AcceptSocket, FIONBIO, &NonBlock) == SOCKET_ERROR){printf("ioctlsocket(FIONBIO) failed with error %d\n", WSAGetLastError());return 1;}elseprintf("ioctlsocket(FIONBIO) is OK!\n");if (CreateSocketInformation(AcceptSocket) == FALSE){printf("CreateSocketInformation(AcceptSocket) failed!\n");return 1;}elseprintf("CreateSocketInformation() is OK!\n");}else{if (WSAGetLastError() != WSAEWOULDBLOCK){printf("accept() failed with error %d\n", WSAGetLastError());return 1;}elseprintf("accept() is fine!\n");}}// 依次处理所有的套接字,SocketInfo为当前要处理的套接字信息for (i = 0; Total > 0 && i < TotalSockets; i++){LPSOCKET_INFORMATION SocketInfo = SocketArray[i];// 判断当前套接字的可读性,即是否有接入的连接请求或者可以接受数据if (FD_ISSET(SocketInfo->Socket, &ReadSet)){Total--;SocketInfo->DataBuf.buf = SocketInfo->Buffer;SocketInfo->DataBuf.len = DATA_BUFSIZE;Flags = 0;if (WSARecv(SocketInfo->Socket, &(SocketInfo->DataBuf), 1, &RecvBytes,&Flags, NULL, NULL) == SOCKET_ERROR){if (WSAGetLastError() != WSAEWOULDBLOCK){printf("WSARecv() failed with error %d\n", WSAGetLastError());FreeSocketInformation(i);}elseprintf("WSARecv() is OK!\n");continue;}else{SocketInfo->BytesRECV = RecvBytes;// 如果接收到0个字节,则表示对方关闭连接if (RecvBytes == 0){FreeSocketInformation(i);continue;}}}// 如果当前套接字在WriteSet集合中// 则表明if (FD_ISSET(SocketInfo->Socket, &WriteSet)){Total--;SocketInfo->DataBuf.buf = SocketInfo->Buffer + SocketInfo->BytesSEND;SocketInfo->DataBuf.len = SocketInfo->BytesRECV - SocketInfo->BytesSEND;if (WSASend(SocketInfo->Socket, &(SocketInfo->DataBuf), 1, &SendBytes, 0,NULL, NULL) == SOCKET_ERROR){if (WSAGetLastError() != WSAEWOULDBLOCK){printf("WSASend() failed with error %d\n", WSAGetLastError());FreeSocketInformation(i);}elseprintf("WSASend() is OK!\n");continue;}else{SocketInfo->BytesSEND += SendBytes;if (SocketInfo->BytesSEND == SocketInfo->BytesRECV){SocketInfo->BytesSEND = 0;SocketInfo->BytesRECV = 0;}}}}}
}BOOL CreateSocketInformation(SOCKET s)
{LPSOCKET_INFORMATION SI;printf("Accepted socket number %d\n", s);if ((SI = (LPSOCKET_INFORMATION)GlobalAlloc(GPTR, sizeof(SOCKET_INFORMATION))) == NULL){printf("GlobalAlloc() failed with error %d\n", GetLastError());return FALSE;}elseprintf("GlobalAlloc() for SOCKET_INFORMATION is OK!\n");// Prepare SocketInfo structure for useSI->Socket = s;SI->BytesSEND = 0;SI->BytesRECV = 0;SocketArray[TotalSockets] = SI;TotalSockets++;return(TRUE);
}void FreeSocketInformation(DWORD Index)
{LPSOCKET_INFORMATION SI = SocketArray[Index];DWORD i;closesocket(SI->Socket);printf("Closing socket number %d\n", SI->Socket);GlobalFree(SI);// Squash the socket arrayfor (i = Index; i < TotalSockets; i++){SocketArray[i] = SocketArray[i + 1];}TotalSockets--;
}

运行结果:
服务器:
在这里插入图片描述
客户机:
在这里插入图片描述

2.WSAEventSelect服务器

// WSAEventSelect模型回送服务器
// WSAEventSelect.cpp
#include <winsock2.h>
#include <windows.h>
#include <stdio.h>
#pragma comment(lib,"ws2_32.lib")
#define PORT 5150
#define DATA_BUFSIZE 8192typedef struct _SOCKET_INFORMATION {CHAR Buffer[DATA_BUFSIZE];WSABUF DataBuf;SOCKET Socket;DWORD BytesSEND;DWORD BytesRECV;
} SOCKET_INFORMATION, *LPSOCKET_INFORMATION;BOOL CreateSocketInformation(SOCKET s);
void FreeSocketInformation(DWORD Event);DWORD EventTotal = 0;
WSAEVENT EventArray[WSA_MAXIMUM_WAIT_EVENTS];
LPSOCKET_INFORMATION SocketArray[WSA_MAXIMUM_WAIT_EVENTS];int main(int argc, char **argv)
{SOCKET Listen;SOCKET Accept;SOCKADDR_IN InternetAddr;LPSOCKET_INFORMATION SocketInfo;DWORD Event;WSANETWORKEVENTS NetworkEvents;WSADATA wsaData;DWORD Flags;DWORD RecvBytes;DWORD SendBytes;if (WSAStartup(0x0202, &wsaData) != 0){printf("WSAStartup() failed with error %d\n", WSAGetLastError());return 1;}elseprintf("WSAStartup() is OK!\n");if ((Listen = socket(AF_INET, SOCK_STREAM, 0)) == INVALID_SOCKET){printf("socket() failed with error %d\n", WSAGetLastError());return 1;}elseprintf("socket() is OK!\n");if (CreateSocketInformation(Listen) == FALSE)printf("CreateSocketInformation() failed!\n");elseprintf("CreateSocketInformation() is OK lol!\n");if (WSAEventSelect(Listen, EventArray[EventTotal - 1], FD_ACCEPT | FD_CLOSE) == SOCKET_ERROR){printf("WSAEventSelect() failed with error %d\n", WSAGetLastError());return 1;}elseprintf("WSAEventSelect() is pretty fine!\n");InternetAddr.sin_family = AF_INET;InternetAddr.sin_addr.s_addr = htonl(INADDR_ANY);InternetAddr.sin_port = htons(PORT);if (bind(Listen, (PSOCKADDR)&InternetAddr, sizeof(InternetAddr)) == SOCKET_ERROR){printf("bind() failed with error %d\n", WSAGetLastError());return 1;}elseprintf("bind() is OK!\n");if (listen(Listen, 5)){printf("listen() failed with error %d\n", WSAGetLastError());return 1;}elseprintf("listen() is OK!\n");while (TRUE){// 等待套接字接受I/O通知if ((Event = WSAWaitForMultipleEvents(EventTotal, EventArray, FALSE, WSA_INFINITE, FALSE)) == WSA_WAIT_FAILED){printf("WSAWaitForMultipleEvents() failed with error %d\n", WSAGetLastError());return 1;}elseprintf("WSAWaitForMultipleEvents() is pretty damn OK!\n");if (WSAEnumNetworkEvents(SocketArray[Event - WSA_WAIT_EVENT_0]->Socket,EventArray[Event - WSA_WAIT_EVENT_0], &NetworkEvents) == SOCKET_ERROR){printf("WSAEnumNetworkEvents() failed with error %d\n", WSAGetLastError());return 1;}elseprintf("WSAEnumNetworkEvents() should be fine!\n");if (NetworkEvents.lNetworkEvents & FD_ACCEPT){if (NetworkEvents.iErrorCode[FD_ACCEPT_BIT] != 0){printf("FD_ACCEPT failed with error %d\n", NetworkEvents.iErrorCode[FD_ACCEPT_BIT]);break;}if ((Accept = accept(SocketArray[Event - WSA_WAIT_EVENT_0]->Socket, NULL, NULL)) == INVALID_SOCKET){printf("accept() failed with error %d\n", WSAGetLastError());break;}elseprintf("accept() should be OK!\n");if (EventTotal > WSA_MAXIMUM_WAIT_EVENTS){printf("Too many connections - closing socket...\n");closesocket(Accept);break;}CreateSocketInformation(Accept);if (WSAEventSelect(Accept, EventArray[EventTotal - 1], FD_READ | FD_WRITE | FD_CLOSE) == SOCKET_ERROR){printf("WSAEventSelect() failed with error %d\n", WSAGetLastError());return 1;}elseprintf("WSAEventSelect() is OK!\n");printf("Socket %d got connected...\n", Accept);}// 如果读取和写入事件发生,试着对数据缓冲区读取和写入数据if (NetworkEvents.lNetworkEvents & FD_READ || NetworkEvents.lNetworkEvents & FD_WRITE){if (NetworkEvents.lNetworkEvents & FD_READ && NetworkEvents.iErrorCode[FD_READ_BIT] != 0){printf("FD_READ failed with error %d\n", NetworkEvents.iErrorCode[FD_READ_BIT]);break;}elseprintf("FD_READ is OK!\n");if (NetworkEvents.lNetworkEvents & FD_WRITE && NetworkEvents.iErrorCode[FD_WRITE_BIT] != 0){printf("FD_WRITE failed with error %d\n", NetworkEvents.iErrorCode[FD_WRITE_BIT]);break;}elseprintf("FD_WRITE is OK!\n");SocketInfo = SocketArray[Event - WSA_WAIT_EVENT_0];// 当收到的字节数为0时读取数据if (SocketInfo->BytesRECV == 0){SocketInfo->DataBuf.buf = SocketInfo->Buffer;SocketInfo->DataBuf.len = DATA_BUFSIZE;Flags = 0;if (WSARecv(SocketInfo->Socket, &(SocketInfo->DataBuf), 1, &RecvBytes,&Flags, NULL, NULL) == SOCKET_ERROR){if (WSAGetLastError() != WSAEWOULDBLOCK){printf("WSARecv() failed with error %d\n", WSAGetLastError());FreeSocketInformation(Event - WSA_WAIT_EVENT_0);return 1;}}else{printf("WSARecv() is working!\n");SocketInfo->BytesRECV = RecvBytes;}}// 当收到的字节数大于发送的字节数时发送数据if (SocketInfo->BytesRECV > SocketInfo->BytesSEND){SocketInfo->DataBuf.buf = SocketInfo->Buffer + SocketInfo->BytesSEND;SocketInfo->DataBuf.len = SocketInfo->BytesRECV - SocketInfo->BytesSEND;if (WSASend(SocketInfo->Socket, &(SocketInfo->DataBuf), 1, &SendBytes, 0,NULL, NULL) == SOCKET_ERROR){if (WSAGetLastError() != WSAEWOULDBLOCK){printf("WSASend() failed with error %d\n", WSAGetLastError());FreeSocketInformation(Event - WSA_WAIT_EVENT_0);return 1;}}else{printf("WSASend() is fine! Thank you...\n");SocketInfo->BytesSEND += SendBytes;if (SocketInfo->BytesSEND == SocketInfo->BytesRECV){SocketInfo->BytesSEND = 0;SocketInfo->BytesRECV = 0;}}}}if (NetworkEvents.lNetworkEvents & FD_CLOSE){if (NetworkEvents.iErrorCode[FD_CLOSE_BIT] != 0){printf("FD_CLOSE failed with error %d\n", NetworkEvents.iErrorCode[FD_CLOSE_BIT]);break;}elseprintf("FD_CLOSE is OK!\n");printf("Closing socket information %d\n", SocketArray[Event - WSA_WAIT_EVENT_0]->Socket);FreeSocketInformation(Event - WSA_WAIT_EVENT_0);}}return 0;
}BOOL CreateSocketInformation(SOCKET s)
{LPSOCKET_INFORMATION SI;if ((EventArray[EventTotal] = WSACreateEvent()) == WSA_INVALID_EVENT){printf("WSACreateEvent() failed with error %d\n", WSAGetLastError());return FALSE;}elseprintf("WSACreateEvent() is OK!\n");if ((SI = (LPSOCKET_INFORMATION)GlobalAlloc(GPTR, sizeof(SOCKET_INFORMATION))) == NULL){printf("GlobalAlloc() failed with error %d\n", GetLastError());return FALSE;}elseprintf("GlobalAlloc() for LPSOCKET_INFORMATION is OK!\n");// 准备使用SocketInfo结构SI->Socket = s;SI->BytesSEND = 0;SI->BytesRECV = 0;SocketArray[EventTotal] = SI;EventTotal++;return(TRUE);
}void FreeSocketInformation(DWORD Event)
{LPSOCKET_INFORMATION SI = SocketArray[Event];DWORD i;closesocket(SI->Socket);GlobalFree(SI);if (WSACloseEvent(EventArray[Event]) == TRUE)printf("WSACloseEvent() is OK!\n\n");elseprintf("WSACloseEvent() failed miserabily!\n\n");// 将套接字和事件从数组删除for (i = Event; i < EventTotal; i++){EventArray[i] = EventArray[i + 1];SocketArray[i] = SocketArray[i + 1];}EventTotal--;
}

运行结果:
服务器:
在这里插入图片描述
客户机:
在这里插入图片描述

3.I/O Completion Port

// I/O完成端口服务器程序
//程序名:IOComplete.cpp#include <winsock2.h>
#include <windows.h>
#include <stdio.h>
#pragma comment(lib,"ws2_32.lib")
#define PORT 5150
#define DATA_B UFSIZE 8192// 类型定义
typedef struct
{OVERLAPPED Overlapped;WSABUF DataBuf;CHAR Buffer[DATA_BUFSIZE];DWORD BytesSEND;DWORD BytesRECV;
} PER_IO_OPERATION_DATA, *LPPER_IO_OPERATION_DATA;// 结构定义
typedef struct
{SOCKET Socket;
} PER_HANDLE_DATA, *LPPER_HANDLE_DATA;// 原型声明
DWORD WINAPI ServerWorkerThread(LPVOID CompletionPortID);int main(int argc, char **argv)
{SOCKADDR_IN InternetAddr;SOCKET Listen;HANDLE ThreadHandle;SOCKET Accept;HANDLE CompletionPort;SYSTEM_INFO SystemInfo;LPPER_HANDLE_DATA PerHandleData;LPPER_IO_OPERATION_DATA PerIoData;int i;DWORD RecvBytes;DWORD Flags;DWORD ThreadID;WSADATA wsaData;DWORD Ret;if ((Ret = WSAStartup((2, 2), &wsaData)) != 0){printf("WSAStartup() failed with error %d\n", Ret);return 1;}elseprintf("WSAStartup() is OK!\n");// 设置一个I/O完成端口if ((CompletionPort = CreateIoCompletionPort(INVALID_HANDLE_VALUE, NULL, 0, 0)) == NULL){printf("CreateIoCompletionPort() failed with error %d\n", GetLastError());return 1;}elseprintf("CreateIoCompletionPort() is damn OK!\n");// 测试系统中有多少CPU处理器GetSystemInfo(&SystemInfo);// 基于系统可用的处理器创建工作线程// 为每个处理器创建两个线程for (i = 0; i < (int)SystemInfo.dwNumberOfProcessors * 2; i++){// 创建一个服务器工作线程,并且传递一个完成端口给这个线程if ((ThreadHandle = CreateThread(NULL, 0, ServerWorkerThread, CompletionPort, 0, &ThreadID)) == NULL){printf("CreateThread() failed with error %d\n", GetLastError());return 1;}elseprintf("CreateThread() is OK!\n");// 关闭线程句柄CloseHandle(ThreadHandle);}// 创建服务器监听套接字if ((Listen = WSASocket(AF_INET, SOCK_STREAM, 0, NULL, 0, WSA_FLAG_OVERLAPPED)) == INVALID_SOCKET){printf("WSASocket() failed with error %d\n", WSAGetLastError());return 1;}elseprintf("WSASocket() is OK!\n");InternetAddr.sin_family = AF_INET;InternetAddr.sin_addr.s_addr = htonl(INADDR_ANY);InternetAddr.sin_port = htons(PORT);if (bind(Listen, (PSOCKADDR)&InternetAddr, sizeof(InternetAddr)) == SOCKET_ERROR){printf("bind() failed with error %d\n", WSAGetLastError());return 1;}elseprintf("bind() is fine!\n");// 开始监听if (listen(Listen, 5) == SOCKET_ERROR){printf("listen() failed with error %d\n", WSAGetLastError());return 1;}elseprintf("listen() is working...\n");// 接受连接并且交给完成端口处理while (TRUE){if ((Accept = WSAAccept(Listen, NULL, NULL, NULL, 0)) == SOCKET_ERROR){printf("WSAAccept() failed with error %d\n", WSAGetLastError());return 1;}elseprintf("WSAAccept() looks fine!\n");// 为套接字分配内存if ((PerHandleData = (LPPER_HANDLE_DATA)GlobalAlloc(GPTR, sizeof(PER_HANDLE_DATA))) == NULL){printf("GlobalAlloc() failed with error %d\n", GetLastError());return 1;}elseprintf("GlobalAlloc() for LPPER_HANDLE_DATA is OK!\n");// 将套接字与完成端口关联起来printf("Socket number %d got connected...\n", Accept);PerHandleData->Socket = Accept;if (CreateIoCompletionPort((HANDLE)Accept, CompletionPort, (DWORD)PerHandleData, 0) == NULL){printf("CreateIoCompletionPort() failed with error %d\n", GetLastError());return 1;}elseprintf("CreateIoCompletionPort() is OK!\n");// 创建一个I/O套接字信息结构体,为下面调用的WSARecv函数服务if ((PerIoData = (LPPER_IO_OPERATION_DATA)GlobalAlloc(GPTR, sizeof(PER_IO_OPERATION_DATA))) == NULL){printf("GlobalAlloc() failed with error %d\n", GetLastError());return 1;}elseprintf("GlobalAlloc() for LPPER_IO_OPERATION_DATA is OK!\n");ZeroMemory(&(PerIoData->Overlapped), sizeof(OVERLAPPED));PerIoData->BytesSEND = 0;PerIoData->BytesRECV = 0;PerIoData->DataBuf.len = DATA_BUFSIZE;PerIoData->DataBuf.buf = PerIoData->Buffer;Flags = 0;if (WSARecv(Accept, &(PerIoData->DataBuf), 1, &RecvBytes, &Flags, &(PerIoData->Overlapped), NULL) == SOCKET_ERROR){if (WSAGetLastError() != ERROR_IO_PENDING){printf("WSARecv() failed with error %d\n", WSAGetLastError());return 1;}}elseprintf("WSARecv() is OK!\n");}//end main
}DWORD WINAPI ServerWorkerThread(LPVOID CompletionPortID)
{HANDLE CompletionPort = (HANDLE)CompletionPortID;DWORD BytesTransferred;LPPER_HANDLE_DATA PerHandleData;LPPER_IO_OPERATION_DATA PerIoData;DWORD SendBytes, RecvBytes;DWORD Flags;while (TRUE){if (GetQueuedCompletionStatus(CompletionPort, &BytesTransferred,(LPDWORD)&PerHandleData, (LPOVERLAPPED *)&PerIoData, INFINITE) == 0){printf("GetQueuedCompletionStatus() failed with error %d\n", GetLastError());return 0;}elseprintf("GetQueuedCompletionStatus() is OK!\n");// 检查套接字是否发生了错误,如果发生了错误,关闭套接字并释放相关内存if (BytesTransferred == 0){printf("Closing socket %d\n", PerHandleData->Socket);if (closesocket(PerHandleData->Socket) == SOCKET_ERROR){printf("closesocket() failed with error %d\n", WSAGetLastError());return 0;}elseprintf("closesocket() is fine!\n");GlobalFree(PerHandleData);GlobalFree(PerIoData);continue;}// 如果ByteRECV字段等于0,表示一个WSARecv调用刚刚完成if (PerIoData->BytesRECV == 0){PerIoData->BytesRECV = BytesTransferred;PerIoData->BytesSEND = 0;//printf("客户消息:%s\n",PerIoData->DataBuf.buf);}else{PerIoData->BytesSEND += BytesTransferred;}if (PerIoData->BytesRECV > PerIoData->BytesSEND){// 调用WSASend()发送,直到所有收到的字节被发送ZeroMemory(&(PerIoData->Overlapped), sizeof(OVERLAPPED));PerIoData->DataBuf.buf = PerIoData->Buffer + PerIoData->BytesSEND;PerIoData->DataBuf.len = PerIoData->BytesRECV - PerIoData->BytesSEND;if (WSASend(PerHandleData->Socket, &(PerIoData->DataBuf), 1, &SendBytes, 0,&(PerIoData->Overlapped), NULL) == SOCKET_ERROR){if (WSAGetLastError() != ERROR_IO_PENDING){printf("WSASend() failed with error %d\n", WSAGetLastError());return 0;}}elseprintf("WSASend() is OK!\n");}else{PerIoData->BytesRECV = 0;// 现在没有多余的数据可以发送,发出另外一个WSARecv()请求Flags = 0;ZeroMemory(&(PerIoData->Overlapped), sizeof(OVERLAPPED));PerIoData->DataBuf.len = DATA_BUFSIZE;PerIoData->DataBuf.buf = PerIoData->Buffer;if (WSARecv(PerHandleData->Socket, &(PerIoData->DataBuf), 1, &RecvBytes, &Flags,&(PerIoData->Overlapped), NULL) == SOCKET_ERROR){if (WSAGetLastError() != ERROR_IO_PENDING){printf("WSARecv() failed with error %d\n", WSAGetLastError());return 0;}}elseprintf("WSARecv() is OK!\n");}}
}

运行结果:
服务器:
在这里插入图片描述
客户机:
在这里插入图片描述


这篇关于【通信协议及编码】实验2:三种I/O模型回送服务器程序设计的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/442158

相关文章

大模型研发全揭秘:客服工单数据标注的完整攻略

在人工智能(AI)领域,数据标注是模型训练过程中至关重要的一步。无论你是新手还是有经验的从业者,掌握数据标注的技术细节和常见问题的解决方案都能为你的AI项目增添不少价值。在电信运营商的客服系统中,工单数据是客户问题和解决方案的重要记录。通过对这些工单数据进行有效标注,不仅能够帮助提升客服自动化系统的智能化水平,还能优化客户服务流程,提高客户满意度。本文将详细介绍如何在电信运营商客服工单的背景下进行

不懂推荐算法也能设计推荐系统

本文以商业化应用推荐为例,告诉我们不懂推荐算法的产品,也能从产品侧出发, 设计出一款不错的推荐系统。 相信很多新手产品,看到算法二字,多是懵圈的。 什么排序算法、最短路径等都是相对传统的算法(注:传统是指科班出身的产品都会接触过)。但对于推荐算法,多数产品对着网上搜到的资源,都会无从下手。特别当某些推荐算法 和 “AI”扯上关系后,更是加大了理解的难度。 但,不了解推荐算法,就无法做推荐系

Andrej Karpathy最新采访:认知核心模型10亿参数就够了,AI会打破教育不公的僵局

夕小瑶科技说 原创  作者 | 海野 AI圈子的红人,AI大神Andrej Karpathy,曾是OpenAI联合创始人之一,特斯拉AI总监。上一次的动态是官宣创办一家名为 Eureka Labs 的人工智能+教育公司 ,宣布将长期致力于AI原生教育。 近日,Andrej Karpathy接受了No Priors(投资博客)的采访,与硅谷知名投资人 Sara Guo 和 Elad G

Retrieval-based-Voice-Conversion-WebUI模型构建指南

一、模型介绍 Retrieval-based-Voice-Conversion-WebUI(简称 RVC)模型是一个基于 VITS(Variational Inference with adversarial learning for end-to-end Text-to-Speech)的简单易用的语音转换框架。 具有以下特点 简单易用:RVC 模型通过简单易用的网页界面,使得用户无需深入了

透彻!驯服大型语言模型(LLMs)的五种方法,及具体方法选择思路

引言 随着时间的发展,大型语言模型不再停留在演示阶段而是逐步面向生产系统的应用,随着人们期望的不断增加,目标也发生了巨大的变化。在短短的几个月的时间里,人们对大模型的认识已经从对其zero-shot能力感到惊讶,转变为考虑改进模型质量、提高模型可用性。 「大语言模型(LLMs)其实就是利用高容量的模型架构(例如Transformer)对海量的、多种多样的数据分布进行建模得到,它包含了大量的先验

图神经网络模型介绍(1)

我们将图神经网络分为基于谱域的模型和基于空域的模型,并按照发展顺序详解每个类别中的重要模型。 1.1基于谱域的图神经网络         谱域上的图卷积在图学习迈向深度学习的发展历程中起到了关键的作用。本节主要介绍三个具有代表性的谱域图神经网络:谱图卷积网络、切比雪夫网络和图卷积网络。 (1)谱图卷积网络 卷积定理:函数卷积的傅里叶变换是函数傅里叶变换的乘积,即F{f*g}

秋招最新大模型算法面试,熬夜都要肝完它

💥大家在面试大模型LLM这个板块的时候,不知道面试完会不会复盘、总结,做笔记的习惯,这份大模型算法岗面试八股笔记也帮助不少人拿到过offer ✨对于面试大模型算法工程师会有一定的帮助,都附有完整答案,熬夜也要看完,祝大家一臂之力 这份《大模型算法工程师面试题》已经上传CSDN,还有完整版的大模型 AI 学习资料,朋友们如果需要可以微信扫描下方CSDN官方认证二维码免费领取【保证100%免费

【生成模型系列(初级)】嵌入(Embedding)方程——自然语言处理的数学灵魂【通俗理解】

【通俗理解】嵌入(Embedding)方程——自然语言处理的数学灵魂 关键词提炼 #嵌入方程 #自然语言处理 #词向量 #机器学习 #神经网络 #向量空间模型 #Siri #Google翻译 #AlexNet 第一节:嵌入方程的类比与核心概念【尽可能通俗】 嵌入方程可以被看作是自然语言处理中的“翻译机”,它将文本中的单词或短语转换成计算机能够理解的数学形式,即向量。 正如翻译机将一种语言

怎么让1台电脑共享给7人同时流畅设计

在当今的创意设计与数字内容生产领域,图形工作站以其强大的计算能力、专业的图形处理能力和稳定的系统性能,成为了众多设计师、动画师、视频编辑师等创意工作者的必备工具。 设计团队面临资源有限,比如只有一台高性能电脑时,如何高效地让七人同时流畅地进行设计工作,便成为了一个亟待解决的问题。 一、硬件升级与配置 1.高性能处理器(CPU):选择多核、高线程的处理器,例如Intel的至强系列或AMD的Ry

AI Toolkit + H100 GPU,一小时内微调最新热门文生图模型 FLUX

上个月,FLUX 席卷了互联网,这并非没有原因。他们声称优于 DALLE 3、Ideogram 和 Stable Diffusion 3 等模型,而这一点已被证明是有依据的。随着越来越多的流行图像生成工具(如 Stable Diffusion Web UI Forge 和 ComyUI)开始支持这些模型,FLUX 在 Stable Diffusion 领域的扩展将会持续下去。 自 FLU