select函数用法问题!!!!1
这段测试代码是服务器端的代码,
问题描述:当客户端进行连接的时候,连接成功,只能发送一次数据,第二次发送的数据服务器端接受不到,而且select函数也检测不到客户端发送数据到来。
请大家帮忙找下原因,偶是菜鸟。。。
#include <iostream>#include <Windows.h>#include <WinSock.h>#include <time.h>using namespace std;#pragma warning (disable:4996)#pragma comment (lib,"ws2_32.lib")#define PORT 4000#define IP_ADDRESS "127.0.0.1"int main(){ WSADATA Ws; int Ret = 0; int AddrLen = 0; HANDLE hThread = NULL; char RecvBuffer[256] = {0}; SOCKET ServerSocket, ClientSocket; struct sockaddr_in LocalAddr, ClientAddr; fd_set fdread; fd_set fdwrite; timeval tv; int select_result; if(WSAStartup(MAKEWORD(2,2), &Ws) != 0) { cout<<"Init windows socket failed"<<GetLastError()<<endl; return -1; } ServerSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if(ServerSocket == INVALID_SOCKET) { cout<<"Create socket failed"<<endl; return -1; } LocalAddr.sin_family = AF_INET; LocalAddr.sin_addr.S_un.S_addr = inet_addr(IP_ADDRESS); LocalAddr.sin_port = htons(PORT); memset(LocalAddr.sin_zero, 0x00, 8); Ret = bind(ServerSocket, (struct sockaddr*)&LocalAddr, sizeof(LocalAddr)); if(Ret != 0) { cout<<"Bind socket failed"<<endl; return -1; } Ret = listen(ServerSocket, 10); if(Ret != 0) { cout<<"listen socket failed"<<endl; return -1; } cout<<"server start...."<<endl; while(1) { FD_ZERO(&fdread); FD_ZERO(&fdwrite); FD_SET(ServerSocket, &fdread); FD_SET(ServerSocket, &fdwrite); tv.tv_sec = 10; tv.tv_usec = 0; cout<<"select start"<<endl; select_result = select(0, &fdread, &fdwrite, NULL, &tv); AddrLen = sizeof(ClientAddr); if(select_result > 0) { cout<<"select result == "<<select_result<<endl; for(int i = 0; i < (int)fdread.fd_count; i++) { cout<<" i == "<<i<<endl; if(FD_ISSET(fdread.fd_array[i], &fdread)) { ClientSocket = accept(fdread.fd_array[i], (struct sockaddr*)&ClientAddr, &AddrLen); cout<<"Connected from " <<inet_ntoa(ClientAddr.sin_addr)<<endl; Ret = recv(ClientSocket, RecvBuffer, 256, 0); if(Ret == 0 || Ret == SOCKET_ERROR) { cout<<"client quit"<<endl; } cout<<"Recv Msg is: "<<RecvBuffer<<endl; memset(RecvBuffer, 0, 256); } else { Ret = recv(fdread.fd_array[i], RecvBuffer, 256, 0); if(Ret > 0) { cout<<"Recv msg "<<RecvBuffer<<endl; } else { closesocket(fdread.fd_array[i]); cout<<"close one client"<<endl; FD_CLR(fdread.fd_array[i], &fdread); } } } } } closesocket(ServerSocket); closesocket(ClientSocket); WSACleanup(); return 0;}