Windows Socket编程的大致过程:
服务器端:
----过程-------------对应的API-------
0.初始化 | WSAStartup()
1.创建Socket | socket()
2.绑定Socket | bind()
3.监听 | listen()
4.接受连接 | accept()
5.接收/发送数据 | recv()/send()
6.关闭socket | closesocket()
7.释放资源 | WSACleanup()
_____________________________________
客户端:
0.初始化 | WSAStartup()
1.创建Socket | socket()
2.连接Socket | connect()
3.接收/发送数据 | recv()/send()
4.关闭socket | closesocket()
5.释放资源 | WSACleanup()
_____________________________________
以下是按照上面所述步骤编写的服务器端和客户端最简单的一个小例子:
0.服务器端代码:
// FileName: Server.cpp // 服务器端 #include<stdio.h> #include<winsock.h> #include<windows.h> #pragma comment(lib,"ws2_32") #define PORT 2012 #define IP "127.0.0.1" void main() { // 0.初始化 WSADATA wsaData; WSAStartup(0x0202, &wsaData); // 1.创建Socket SOCKET sockServer; sockServer = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); // 2.绑定Socket struct sockaddr_in sockaddrServer; sockaddrServer.sin_family = AF_INET; sockaddrServer.sin_addr.S_un.S_addr = inet_addr(IP); sockaddrServer.sin_port = htons(PORT); memset(sockaddrServer.sin_zero, 0x00, 8); bind(sockServer, (struct sockaddr*)&sockaddrServer, sizeof(sockaddrServer)); // 3.监听 listen(sockServer, 0); // 4.接受连接 struct sockaddr_in sockaddrClient; // 用于存放客户端地址信息 int addrlen = sizeof(sockaddrClient); SOCKET sockClient = accept(sockServer, (struct sockaddr*)&sockaddrClient, &addrlen); printf("IP: %s\n", inet_ntoa(sockaddrClient.sin_addr)); printf("PORT: %d\n", ntohs(sockaddrClient.sin_port)); // 5.recv char buf[64] = {0}; recv(sockClient, buf, 64, 0); printf("Recv buf = %s\n", buf); // 6.关闭Socket closesocket(sockServer); // 7.释放资源 WSACleanup(); }
1.客户端代码:
// FileName: Client.cpp // 客户端 #include<stdio.h> #include<winsock.h> #pragma comment(lib, "ws2_32") #define IP "127.0.0.1" #define PORT 2012 void main() { // 0.初始化 WSADATA wsaData; WSAStartup(0x0202, &wsaData); // 1.绑定Socket SOCKET sockServer= socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); // 2.连接Socket struct sockaddr_in sockaddrServer; sockaddrServer.sin_family = AF_INET; sockaddrServer.sin_addr.S_un.S_addr = inet_addr(IP); sockaddrServer.sin_port = htons(2012); memset(sockaddrServer.sin_zero, 0x00, 8); connect(sockServer, (struct sockaddr*)&sockaddrServer, sizeof(sockaddrServer)); // 3.send send(sockServer, "helloworld", strlen("helloworld"), 0); // 4.关闭Socket closesocket(sockServer); // 5.释放资源 WSACleanup(); }