基于Windows的套接字相关函数及示例

链接ws2_32.lib库

头文件#include <winsock2.h>

Winsock初始化

1  int WSAStartup(WORD wVersionRequested,LPWSADATA lpWSAData);

wVersionRequested:Winsock版本信息,用MAKEWORD宏构造,MAKEWORD(2,2)。

lpWSAData:WSADATA结构体变量的地址。

 

 

 1 #include <WinSock2.h>
 2 #include <iostream>
 3 
 4 namespace WinSock {
 5 
 6     void ErrorHandling(char* message) {
 7         std::cerr << message << std::endl;
 8         exit(1);
 9     }
10 
11     int Server(int port) {
12         WSADATA wsaData;
13         SOCKET hServSock, hClntSock;
14         SOCKADDR_IN servAddr, clntAddr;
15         int szClntAddr;
16         char message[] = "Hello World!";
17         if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0) ErrorHandling("WSAStartup() error");
18         hServSock = socket(PF_INET, SOCK_STREAM, 0);
19         if (hServSock == INVALID_SOCKET) ErrorHandling("socket() error");
20         memset(&servAddr, 0, sizeof(servAddr));
21         servAddr.sin_family = AF_INET;
22         servAddr.sin_addr.S_un.S_addr = htonl(INADDR_ANY);
23         servAddr.sin_port = htons(port);
24         if (bind(hServSock, (SOCKADDR*)&servAddr, sizeof(servAddr)) == SOCKET_ERROR) ErrorHandling("bind() error");
25         if (listen(hServSock, 5) == SOCKET_ERROR) ErrorHandling("listen() error");
26         szClntAddr = sizeof(clntAddr);
27         hClntSock = accept(hServSock, (SOCKADDR*)&clntAddr, &szClntAddr);
28         if (hClntSock == INVALID_SOCKET) ErrorHandling("accept() error");
29         send(hClntSock, message, sizeof(message), 0);
30         closesocket(hClntSock);
31         closesocket(hServSock);
32         WSACleanup();
33         return 0;
34     }
35 
36     int Client(char ip[], int port) {
37         WSADATA wsaData;
38         SOCKET hSocket;
39         SOCKADDR_IN servAddr;
40         char message[30];
41         int strLen;
42         if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0) ErrorHandling("WSAStartup() error");
43         hSocket = socket(PF_INET, SOCK_STREAM, 0);
44         if (hSocket == INVALID_SOCKET) ErrorHandling("socket() error");
45         memset(&servAddr, 0, sizeof(servAddr));
46         servAddr.sin_family = AF_INET;
47         servAddr.sin_addr.S_un.S_addr = inet_addr(ip);
48         servAddr.sin_port = htons(port);
49         if (connect(hSocket, (SOCKADDR*)&servAddr, sizeof(servAddr)) == SOCKET_ERROR) ErrorHandling("connect() error");
50         strLen = recv(hSocket, message, sizeof(message) - 1, 0);
51         if (strLen == -1) ErrorHandling("read() error");
52         std::cout << "Message from server: " << message << std::endl;
53         closesocket(hSocket);
54         WSACleanup();
55         return 0;
56     }
57 
58 };

 

基于Windows的套接字相关函数及示例

上一篇:MyBatis介绍


下一篇:Elasticsearch 创始人 Shay Banon:让数据自己说话