1 // StockSrv.cpp : 定义控制台应用程序的入口点。 2 // 3 4 #include "stdafx.h" 5 #include <iostream> 6 #include <process.h> 7 #include <WinSock2.h> 8 #pragma comment(lib,"Ws2_32.lib") //fatal error LNK1120: 12 个无法解析的外部命令 9 10 using namespace std; 11 #define PORT 8090 12 13 //子线程函数需要放调用者的前面 14 unsigned int __stdcall RecvThreadFunc( void* pArguments ) 15 { 16 printf("RecvThreadFunc:ID号 = %4d is starting!\n", GetCurrentThreadId()); 17 SOCKET ClientSocket = (SOCKET)pArguments; 18 19 //接收数据 20 char recvBuf[100]; 21 recv(ClientSocket,recvBuf,100,0); 22 printf("recvBuf = %s\n",recvBuf); 23 24 //发送数据 25 char sendBuf[100]; 26 sprintf_s(sendBuf,"test data:sendBuf"); 27 send(ClientSocket,sendBuf,strlen(sendBuf)+1,0); 28 printf("sendBuf = %s\n",sendBuf); 29 30 _endthreadex( 0 ); //释放 threadIDdata, 再 ExitThread() 31 return 0; 32 } 33 34 int _tmain(int argc, _TCHAR* argv[]) 35 { 36 37 WORD wVersionRequested; 38 WSADATA wsaData; //WSADATA 结构体主要包含了系统所支持的Winsock版本信息 39 int err; 40 41 wVersionRequested = MAKEWORD(2,2); 42 err = WSAStartup(wVersionRequested,&wsaData); //加载套接字库 43 if (err != 0) 44 { 45 cout << "初始化 Socket 失败:" << GetLastError() << endl; 46 return 0; 47 } 48 if (LOBYTE(wsaData.wVersion) != 2 || HIBYTE(wsaData.wVersion) != 2) 49 { 50 WSACleanup(); 51 return 0; 52 } 53 54 //创建用于监听的套接字 55 SOCKET sockSrv = socket(AF_INET,SOCK_STREAM,0); 56 57 SOCKADDR_IN addrSrv,addrClient; //TCP/IP 套接字指定套接字的地址 58 addrSrv.sin_addr.S_un.S_addr = htonl(INADDR_ANY); 59 addrSrv.sin_family = AF_INET; 60 addrSrv.sin_port = htons(PORT); 61 int len = sizeof(SOCKADDR); 62 //绑定套接字 63 if(bind(sockSrv,(SOCKADDR*)&addrSrv,sizeof(SOCKADDR)) != 0) 64 { 65 cout<<"绑定 Socket 失败:"<<GetLastError()<<endl; 66 return 0; 67 } 68 //将套接字设为监听模式,准备接收客户请求 69 if(listen(sockSrv,5) == SOCKET_ERROR) 70 { 71 return 0; 72 } 73 cout << "服务端已经启动,正在监听" << endl; 74 while (TRUE) 75 { 76 //等待客户请求到来 77 SOCKET sockConn = accept(sockSrv,(SOCKADDR*)&addrClient,&len); 78 79 unsigned threadID; 80 HANDLE hThread = (HANDLE)_beginthreadex(NULL,0,RecvThreadFunc,(void *)sockConn,0, &threadID); 81 WaitForSingleObject(hThread, INFINITE); //阻塞等待新线程结束 82 CloseHandle(hThread); //关闭句柄 83 84 //关闭套接字 85 closesocket(sockConn); 86 } 87 return 0; 88 }
时间: 2024-10-06 00:57:41