1 // WindowsSocketServer.cpp : 定义控制台应用程序的入口点。 2 // 3 4 #include "stdafx.h" 5 #include 6 #include 7 #include 8 #include 9 #include 10 #pragma comment(lib,"Ws2_32.lib") 11 12 using namespace std; 13 #define PORT 8080 14 #define IP_ADDRESS "172.16.20.181" 15 CRITICAL_SECTION cs; 16 //#define CLIENT_PORT 8081 17 ///#define CLIENT_IP_ADDRESS "172.16.20.181" 18 19 //接收每个客户端连接的处理函数 20 DWORD WINAPI ClientThread(LPVOID lpParameter); 21 22 //连接和服务器端有连接的客户端 23 DWORD WINAPI ConnectClientsThread(LPVOID lpParameter); 24 25 int main(int argc, char* argv[]) 26 { 27 //HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE); 28 //SetConsoleTextAttribute(hConsole,FOREGROUND_GREEN); 29 InitializeCriticalSection(&cs); 30 //初始化事件和关键段,自动置位,初始无触发的匿名事件 31 //g_hThreadEvent = CreateEvent(NULL,FALSE,FALSE,NULL); 32 33 //system("ipconfig /all >log.txt"); 34 //WSADATA 结构体主要包含了系统所支持的Winsock版本信息 35 WSADATA Ws; 36 SOCKET ServerSocket, ClientSocket; 37 //TCP/IP 套接字指定套接字的地址 38 struct sockaddr_in LocalAddr, ClientAddr; 39 int Ret = 0; 40 int AddrLen = 0; 41 HANDLE hThread = NULL; 42 HANDLE hConnectThread = NULL; 43 //Init Windows Socket 44 //The WSAStartup function initiates use of WS2_32.DLL by a process. 45 //初始化Winsock2.2.使用WSAStartup函数 46 //第一个参数是所要用的Winsock版本号 47 //The MAKEWORD macro creates a WORD value by concatenating the specified values. 48 //第二个参数就是WSADATA 结构体的指针。如果初始化成功则返回0 49 //要注意任何WinsockAPI函数都必须在初始化后使用,包括错误检查函数 50 if ( WSAStartup(MAKEWORD(2,2), &Ws) != 0 ) 51 { 52 cout<<"初始化 Socket 失败:"< < =0 && line.length() > 0)184 {185 string clientIp = line.substr(0,index);186 string clientPort = line.substr(index+1);187 ClientAddr.sin_family = AF_INET;188 ClientAddr.sin_addr.s_addr = inet_addr(clientIp.c_str());189 ClientAddr.sin_port = htons((unsigned short)clientPort.c_str());190 191 //设置ServerAddr中前8个字符为0x00192 memset(ClientAddr.sin_zero, 0x00, 8);193 194 Ret = connect(ServerSocket,(struct sockaddr*)&ClientAddr, sizeof(ClientAddr));195 196 if( Ret == SOCKET_ERROR )197 {198 cout<<"服务端的方法 ConnectClients 在 建立与:"< <<":"< <<"连接过程发生错误:"< < logs.txt\""">"; 228 229 Ret = send(ClientSocket, SendBuffer, (int)strlen(SendBuffer), 0);230 if ( Ret == SOCKET_ERROR )231 {232 cout<<"发送消息失败:"< <
1 // WindowsSocketClient.cpp : 定义控制台应用程序的入口点。 2 // 3 4 #include "stdafx.h" 5 #include 6 #include 7 #include 8 #include 9 #include