用标准C语言在window环境下写基于tcp协议的socket通信
时间: 2023-12-21 15:07:19 浏览: 94
Windows环境下socket编程(C语言编写)
5星 · 资源好评率100%
以下是基于TCP协议的socket通信的示例代码,使用标准C语言在Windows环境下编写:
```c
#include <stdio.h>
#include <winsock2.h>
#pragma comment(lib, "ws2_32.lib")
int main() {
// 初始化Winsock库
WSADATA wsaData;
if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0) {
printf("WSAStartup failed\n");
return 1;
}
// 创建socket
SOCKET server_socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (server_socket == INVALID_SOCKET) {
printf("socket creation failed\n");
return 1;
}
// 绑定socket到本地IP和端口
struct sockaddr_in server_addr = {0};
server_addr.sin_family = AF_INET;
server_addr.sin_addr.s_addr = htonl(INADDR_ANY);
server_addr.sin_port = htons(12345);
if (bind(server_socket, (struct sockaddr*)&server_addr, sizeof(server_addr)) == SOCKET_ERROR) {
printf("socket binding failed\n");
closesocket(server_socket);
return 1;
}
// 监听端口
if (listen(server_socket, SOMAXCONN) == SOCKET_ERROR) {
printf("socket listening failed\n");
closesocket(server_socket);
return 1;
}
printf("Waiting for incoming connections...\n");
// 接受客户端连接请求
struct sockaddr_in client_addr = {0};
int client_addr_len = sizeof(client_addr);
SOCKET client_socket = accept(server_socket, (struct sockaddr*)&client_addr, &client_addr_len);
if (client_socket == INVALID_SOCKET) {
printf("client connection failed\n");
closesocket(server_socket);
return 1;
}
printf("Client connected: %s:%d\n", inet_ntoa(client_addr.sin_addr), ntohs(client_addr.sin_port));
// 接收客户端的消息
char buffer[1024];
int recv_size;
while ((recv_size = recv(client_socket, buffer, sizeof(buffer), 0)) > 0) {
buffer[recv_size] = '\0';
printf("Received message: %s\n", buffer);
// 发送回复消息
if (send(client_socket, "Hello from server", 18, 0) == SOCKET_ERROR) {
printf("send failed\n");
closesocket(client_socket);
closesocket(server_socket);
return 1;
}
}
if (recv_size == SOCKET_ERROR) {
printf("recv failed\n");
}
// 关闭socket
closesocket(client_socket);
closesocket(server_socket);
// 卸载Winsock库
WSACleanup();
return 0;
}
```
此示例代码创建了一个TCP服务器,绑定在本地IP地址和端口12345上。它使用`socket()`函数创建一个socket,然后使用`bind()`函数将其绑定到本地地址和端口上。接下来,使用`listen()`函数将socket设置为监听模式,等待客户端的连接请求。一旦有客户端连接,使用`accept()`函数接受它。然后,使用`recv()`函数接收客户端发送的消息,并使用`send()`函数向客户端发送回复消息。最后,关闭客户端和服务器socket,并卸载Winsock库。
需要注意的是,此示例代码仅处理单个客户端连接。如果需要处理多个客户端连接,需要使用多线程或多进程来处理。
阅读全文