// Server.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include <WINSOCK2.H> #pragma comment(lib, "ws2_32.lib ") #define SERVPORT 3333 #define BACKLOG 10 int nCount = 0; int main(int argc, char* argv[]) { printf("socket__WSAStartup__init/n"); WORD wVersion=MAKEWORD(2,0); WSADATA wsData; int nResult= WSAStartup(wVersion,&wsData); if(nResult !=0) { perror("ERROR__socket__WSAStartup/n"); return -1; } int sock_fd,client_fd; struct sockaddr_in my_addr; struct sockaddr_in remote_addr; if ((sock_fd = socket(AF_INET, SOCK_STREAM, 0)) == -1) { perror("ERROR__socket__AF_INET/n"); return -1; } my_addr.sin_family=AF_INET; my_addr.sin_port=htons(SERVPORT); my_addr.sin_addr.s_addr = INADDR_ANY; if (bind(sock_fd, (struct sockaddr *)&my_addr, sizeof(struct sockaddr)) == -1) { perror("ERROR__socket__bind/n"); return -1; } if (listen(sock_fd, BACKLOG) == -1) { perror("ERROR__socket__listen/n"); return -1; } while(1) { printf("accept___start/n"); int sin_size = sizeof(struct sockaddr_in); if ((client_fd = accept(sock_fd, (struct sockaddr *)&remote_addr, &sin_size)) == -1) { perror("ERROR__socket__accept/n"); break; } printf("received a connection from %s/n", inet_ntoa(remote_addr.sin_addr)); struct timeval tv; fd_set readfds; tv.tv_sec = 20; tv.tv_usec = 50000; /* don't care about writefds and exceptfds: */ printf("select___start/n"); while (1) { FD_ZERO(&readfds); FD_SET((u_int)client_fd, &readfds); if(select(0, &readfds, NULL, NULL, &tv) != -1) { if (FD_ISSET(client_fd,&readfds)) { char pRecv[2024] = {0}; int nLen = 0; //¼òµ¥´¦Àí£¬Ö»×÷Ϊ2024³¤¶ÈµÄÊý¾Ý°ü nLen = recv(client_fd,pRecv,2024,0); if(nLen > 2024) { printf("ERROR__received__³¤¶È²»¹»£¬²»´¦Àí/n"); break; } printf("received__%d:%s/n",nCount,pRecv); if (send(client_fd,pRecv,nLen, 0) == -1) { printf("ERROR__send/n"); break; } printf("send__%d:%s/n",nCount++,pRecv); } else { printf("Timed out./n"); } } continue; } printf("select___over/n"); } return 0; }