1.确定Socket版本 WORD tSocketVerNo; WSADATA tVerData; tSocketVerNo = MAKEWORD(2, 0); WSAStartup(tSocketVerNo, &tVerData); 2. 创建一个Socket SOCKET ServerSock; ServerSock = socket( AF_INET, SOCK_STREAM, IPPROTO_TCP); if (ServerSock == INVALID_SOCKET) { closesocket(ServerSock); return -1; } 3.指定服务器的端口号 SOCKADDR_IN local_sin; local_sin.s_addr = INADDR_ANY; local_sin.sin_port = "801"; 4.设置socket属性 int tszOpt = 1; setsockopt(ServerSock,IPPROTO_TCP,SO_REUSEADDR,(char*)&tszOpt,sizeof(tszOpt)); 5.将服务器的端口号绑定到socket上 if (bind( ServerSock, (struct sockaddr FAR *) &local_sin, sizeof(local_sin)) == SOCKET_ERROR) return -1; 6.侦听 if (listen( ServerSock, 4 ) < 0) return -1; 7.建立接收线程 DWORD threadID; CreateThread(NULL,0,(LPTHREAD_START_ROUTINE)AcceptThreadProc,(LPVOID)ServerSock,0,&threadID); 8.接收线程体 void AcceptThreadProc(LPVOID pParam) { SOCKADDR_IN acc_sin; int acc_sin_len; char szMsg[ MY_MSG_LENGTH ]; SOCKET piSocket; piSocket = (SOCKET)pParam; acc_sin_len = sizeof(acc_sin); // 会一直停在这里等待,接通之后返回。 piSocket = accept( piSocket,(struct sockaddr FAR *) &acc_sin,(int FAR *) &acc_sin_len ); if (piSocket < 0) ExitThread(0); // 从socket中读数据 len = recv( piSocket, szMsg, MY_MSG_LENGTH, 0 ); } 9.终止一个socket int EndSocket(int pihsocket) { int tAPIMode; send(pihsocket,(char *) &tAPIMode,0,0); shutdown(pihsocket,2); if (closesocket(pihsocket) == -1) return(-1); return 0; } |
SOCKET服务器端的操作
最新推荐文章于 2024-02-07 10:34:44 发布