#pragma comment(lib, "Ws2_32.lib")
#include <stdio.h> #include <WinSock2.h> #include <WS2tcpip.h> #include <process.h>
#define _LINK_PORT_ 8088 #define _BUFFER_LENGTH_ 512 #define _DEFAULT_PORT_ "12345"
//接受客户端消息的线程函数
unsigned __stdcall ThreadRecv(LPVOID param) { SOCKET ListenSocket = (SOCKET)param;
SOCKET sockClient = INVALID_SOCKET; printf("start accept...
"); sockClient = accept(ListenSocket, NULL, NULL); printf("end accept...
"); if(INVALID_SOCKET == sockClient) { printf("accept failed:%d
", WSAGetLastError()); closesocket(ListenSocket); WSACleanup(); return 1; }
char recvBuf[_BUFFER_LENGTH_] = {0}; int nRecv = 0; while( SOCKET_ERROR != nRecv) { nRecv = recv(sockClient, recvBuf, _BUFFER_LENGTH_, 0); printf("ClinetSocket=%d, received count=%d
", sockClient, nRecv); if(SOCKET_ERROR == nRecv) { //标记当前线程为有信号
_endthreadex(0); printf("recv failed! current thread's state is signaled! error=%d, clientsocket=%d", WSAGetLastError(), sockClient); } }
//关闭Socket
printf("ClientSocket=%d, thread closing...
", sockClient); shutdown(sockClient, SD_BOTH); closesocket( sockClient ); return 0; }
int main() { struct addrinfo *result = NULL, *ptr = NULL, hints; int iResult;
//Initialize winsocket
WSADATA wsaData; iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
ZeroMemory(&hints, sizeof(hints)); hints.ai_family = AF_INET; hints.ai_socktype = SOCK_STREAM; hints.ai_protocol = IPPROTO_IP; hints.ai_flags = AI_PASSIVE;
//Resolve the local address and port to be used by the server;
iResult = getaddrinfo(NULL, _DEFAULT_PORT_, &hints, &result); if(iResult != 0) { printf("getaddrinfo failed: %d
", iResult); WSACleanup(); return 1; }
//Create a SOCKET for the server to listen for client connections
SOCKET ListenSocket = INVALID_SOCKET; ListenSocket = socket(result->ai_family, result->ai_socktype, result->ai_protocol); if(INVALID_SOCKET == ListenSocket) { printf("Error at socket(): %d
", WSAGetLastError()); freeaddrinfo(result); WSACleanup(); return 1; }
//Setup the TCP listening socket
iResult = bind(ListenSocket, result->ai_addr, result->ai_addrlen); if(iResult == SOCKET_ERROR) { printf("bind failed: %d
", WSAGetLastError()); freeaddrinfo(result); closesocket(ListenSocket); WSACleanup(); return 1; }
//Listen connection
if(listen(ListenSocket, SOMAXCONN) == SOCKET_ERROR) { printf("Error at bind():%d
", WSAGetLastError()); closesocket(ListenSocket); WSACleanup(); return 1; }
while(true) { SOCKET sockClient = INVALID_SOCKET;
unsigned threadId; HANDLE hThread = (HANDLE)_beginthreadex(NULL, 0, &ThreadRecv,(void*)ListenSocket, 0, &threadId);
printf("waitting for ClinetSocket to finish...
"); WaitForSingleObject(hThread, INFINITE); CloseHandle(hThread); } WSACleanup();
return 0; } |