1#include <stdio.h>2#include <stdlib.h>3#include <string.h>4#include <winsock2.h>5 6 #defineBuf_size 10247 voidError_handling (Char*message);8 9 intMainintargcChar*argv[])Ten { One wsadata wsadata; A SOCKET Hservsock, Hclntsock; - sockaddr_in servaddr, clntaddr; - timeval timeout; the Fd_set reads, cp_reads; - - intADR_SZ; - intStr_len, I,fd_num; + CharBuf[buf_size]; - + if(ARGC! =2) A { atprintf"usage:%s <port>\n", argv[0]); -Exit1); - } - if(WSAStartup (Makeword (2,2), &wsadata)! =0) -Error_handling ("WSAStartup Error"); - inHservsock = socket (pf_inet, Sock_stream,0); -memset (&SERVADDR,0,sizeof(SERVADDR)); toservaddr.sin_family =af_inet; +Servaddr.sin_addr. S_un. S_ADDR =htonl (inaddr_any); -Servaddr.sin_port = htons (Atoi (argv[1])); the * if(Bind (Hservsock, (sockaddr*) &servaddr,sizeof(SERVADDR)) ==socket_error) $Error_handling ("bind error");Panax Notoginseng if(Listen (Hservsock,5) ==socket_error) -Error_handling ("Listen error"); the +Fd_zero (&reads); AFd_set (Hservsock, &reads); the + while(1) - { $Cp_reads =reads; $Timeout.tv_sec =5; - - if((Fd_num =Select(0, &cp_reads,0,0, &timeout)) = =socket_error) the Break; - if(Fd_num = =0)Wuyi Continue; the - for(i =0; I < reads.fd_count;i++) Wu { - if(Fd_isset (reads.fd_array[i), &cp_reads)) About { $ if(Reads.fd_array[i] = =Hservsock) - { -ADR_SZ =sizeof(CLNTADDR); -Hclntsock = Accept (Hservsock, (sockaddr*) &servaddr, &ADR_SZ); AFd_set (Hclntsock, &reads); +printf"Connected client:%d\n", hclntsock); the } - Else $ { theStr_len = recv (Reads.fd_array[i], buf, Buf_size-1,0); the if(Str_len = =0) the { theFD_CLR (Reads.fd_array[i], &reads); - closesocket (Cp_reads.fd_array[i]); inprintf"closed client:%d\n", Cp_reads.fd_array[i]); the } the Else AboutSend (Reads.fd_array[i], buf, Str_len,0); the } the } the } + } - closesocket (hservsock); the WSACleanup ();Bayi return 0; the } the - voidError_handling (Char*message) - { the fputs (message, stderr); theFPUTC ('\ n', stderr); theExit1); the}
Socket learning Note Using the--select function (Windows)