c语言 tcp方式的聊天室 sercer端 望大家帮我看看 是否有问题
程序代码:
#include<stdio.h> #include<Winsock.h> #include<process.h> #include<string.h> #define PORTNUM 5000 #define MAX_PENDING_CONNECTS 4 typedef struct{ SOCKET Winsock; SOCKADDR_IN local_sin,accept_sin; }PARAMS,*PPARAMS; SOCKADDR_IN local_sin,//the address of local socket accept_sin;//the address of accepted object char szServerA[100]; SOCKET ClientSock = INVALID_SOCKET; // the socket of server and client TCHAR szSendBUffer[100]; //share buffer pool in thread void NetWorkThread(PVOID pvoid) { int err,iReturn; volatile PPARAMS pparams; int accept_sin_len; pparams=(PPARAMS)pvoid; accept_sin_len=sizeof(pparams->accept_sin); /*make accept*/ err=accept(pparams->Winsock,(struct sockaddr *)&(pparams->accept_sin), (int *)&accept_sin_len); //closesocket(pparams->Winsock); if(err==INVALID_SOCKET) //INVALID_SOCKET=-1 printf("Accept error\n"); for(;;) { iReturn=recv(ClientSock,szServerA,sizeof(szServerA),0); if(iReturn == SOCKET_ERROR) { printf("receive data failed\n"); break; } else { printf("%s",szServerA); break; } } /*forbid port*/ shutdown(ClientSock,0x02); /*close ClientSock*/ closesocket(ClientSock); WSACleanup(); } void main() { WORD wVersionRequested; static WSADATA wsaData; static SOCKET Winsock=INVALID_SOCKET; //INVALID_SOCKET=-1 static PARAMS params; int err; /*make WSAStartup for using Socket*/ wVersionRequested = MAKEWORD( 1, 1 ); err = WSAStartup(wVersionRequested, &wsaData ); if(err!=0) printf("WSAStartup error\n"); /*make socket*/ Winsock=socket(AF_INET,SOCK_STREAM,0);//socket function must toLower if(Winsock==INVALID_SOCKET) //INVALID_SOCKET=-1 printf("make socket error\n"); /*fill in the local information of socket */ local_sin.sin_family=AF_INET; local_sin.sin_port = htons(PORTNUM); local_sin.sin_addr.S_un.S_addr = htonl(INADDR_ANY); err=bind(Winsock, (struct sockaddr *)&local_sin, sizeof(local_sin)); if(err==SOCKET_ERROR) //SOCKET_ERROR=-1 printf("Bind error\n"); /*make listen*/ err=listen(Winsock,MAX_PENDING_CONNECTS); //MAX_PENDING_CONNECTS=4 if(err==SOCKET_ERROR) //SOCKET_ERROR=-1 printf("Listen error\n"); params.Winsock = Winsock; params.accept_sin = accept_sin; params.local_sin = local_sin; _beginthread(NetWorkThread,0,¶ms); err=send(ClientSock,szSendBUffer,strlen(szSendBUffer)+1,0); if(err==SOCKET_ERROR) printf("Send error!"); }