求一个程序异步套接口实现一对多通信
求一个程序异步套接口实现一对多通信
给你个框架吧
程序代码:
// VC6 2009-07-26 // server.cpp : 定义控制台应用程序的入口点。UDP // UDP收包程序例子,基于非阻塞模式socket,并利用select() 实现接收超时 #include <stdio.h> #include <Winsock2.h> #pragma comment(lib, "ws2_32.lib") #include "protocol.h" const int port = 8000; const int LINE_LENTH = 20; static states serverState = SERVER_IDLE_STATE; int main() { SOCKET socket1; WSADATA wsaData; int iErrorCode; CMesssage tmpMsg; //states oldState = serverState; initfsm(); // 初始化状态变迁表 if (WSAStartup(MAKEWORD(2,1),&wsaData)) //调用Windows Sockets DLL { printf("Winsock无法初始化!\n"); WSACleanup(); return 0; } printf("服务器开始创建SOCKET。\n"); struct sockaddr_in localAddr; struct sockaddr_in fromAddr; int fromlen = sizeof(fromAddr); localAddr.sin_family = AF_INET; localAddr.sin_port = htons(port); ///监听端口 localAddr.sin_addr.s_addr = INADDR_ANY; ///本机 socket1=socket(AF_INET,SOCK_DGRAM,0); bind(socket1,(struct sockaddr*)&localAddr,sizeof(localAddr)); unsigned long ul = 1; int ret; //设置为非阻塞模式 ret = ioctlsocket (socket1, FIONBIO, (unsigned long*)&ul); if (ret == SOCKET_ERROR) return 0; //select 模型,即设置超时 struct timeval timeout ; fd_set r; while (1) { FD_ZERO (&r); FD_SET (socket1, &r); timeout.tv_sec = 9; //连接超时15秒 timeout.tv_usec = 0; ret = select (0, &r, 0 , 0, &timeout); if ( ret <= 0 ) { ret = WSAGetLastError(); printf("select timeout,%d\n", ret); Sleep(1000); continue; } if( ret > 0) // 未超时 { char buffer[200]="\0"; int revCount; printf("waiting for message from others-------------\n"); revCount = recvfrom(socket1,buffer,sizeof(buffer),0,(struct sockaddr*)&fromAddr,&fromlen); // UDP if (revCount != SOCKET_ERROR) { printf("Received datagram from %s--%s\n",inet_ntoa(fromAddr.sin_addr),buffer); for (int i=1; i < sizeof(buffer) ; i++) { printf("%.2x ", buffer[i-1]); if ( (i % LINE_LENTH) == 0) printf("\n"); } printf("\n"); // 协议解析 ............ } else { int i = WSAGetLastError(); printf("recv time out,error code:%d\n",i); } } } closesocket(socket1); return 1; }