C语言完成Windows系统上的一对一的Socket客户端与服务器程序
时间: 2024-02-18 19:03:46 浏览: 71
C语言实现Socket通信程序
4星 · 用户满意度95%
好的,下面是一个简单的 C 语言 Socket 客户端和服务器程序的示例,适用于 Windows 系统:
服务器端代码:
```c
#include <stdio.h>
#include <winsock2.h>
#pragma comment(lib, "ws2_32.lib")
int main() {
WSADATA wsaData;
SOCKET server_socket, client_socket;
struct sockaddr_in server_addr, client_addr;
char buffer[1024];
// 初始化 Winsock
WSAStartup(MAKEWORD(2, 2), &wsaData);
// 创建 socket
server_socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
// 初始化服务器地址结构体
memset(&server_addr, 0, sizeof(server_addr));
server_addr.sin_family = AF_INET;
server_addr.sin_addr.s_addr = INADDR_ANY;
server_addr.sin_port = htons(8888);
// 绑定 socket 和地址结构体
bind(server_socket, (SOCKADDR *)&server_addr, sizeof(server_addr));
// 监听连接请求
listen(server_socket, 10);
printf("Server started, waiting for clients...\n");
// 接收连接请求
int client_addr_size = sizeof(client_addr);
client_socket = accept(server_socket, (SOCKADDR *)&client_addr, &client_addr_size);
printf("Client connected: %s\n", inet_ntoa(client_addr.sin_addr));
// 接收数据
memset(buffer, 0, sizeof(buffer));
recv(client_socket, buffer, sizeof(buffer), 0);
printf("Received message: %s\n", buffer);
// 发送数据
send(client_socket, "Hello, client!", strlen("Hello, client!"), 0);
// 关闭 socket
closesocket(client_socket);
closesocket(server_socket);
// 释放 Winsock
WSACleanup();
return 0;
}
```
客户端代码:
```c
#include <stdio.h>
#include <winsock2.h>
#pragma comment(lib, "ws2_32.lib")
int main() {
WSADATA wsaData;
SOCKET client_socket;
struct sockaddr_in server_addr;
char buffer[1024];
// 初始化 Winsock
WSAStartup(MAKEWORD(2, 2), &wsaData);
// 创建 socket
client_socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
// 初始化服务器地址结构体
memset(&server_addr, 0, sizeof(server_addr));
server_addr.sin_family = AF_INET;
server_addr.sin_addr.s_addr = inet_addr("127.0.0.1");
server_addr.sin_port = htons(8888);
// 连接服务器
connect(client_socket, (SOCKADDR *)&server_addr, sizeof(server_addr));
// 发送数据
send(client_socket, "Hello, server!", strlen("Hello, server!"), 0);
// 接收数据
memset(buffer, 0, sizeof(buffer));
recv(client_socket, buffer, sizeof(buffer), 0);
printf("Received message: %s\n", buffer);
// 关闭 socket
closesocket(client_socket);
// 释放 Winsock
WSACleanup();
return 0;
}
```
以上代码实现了一个简单的一对一 Socket 通信,服务器端监听端口 8888,客户端连接服务器,并发送一条消息,服务器接收到消息后回复一条消息。当客户端接收到服务器的回复消息后,程序结束。注意:Windows 系统下需要引入 `winsock2.h` 头文件并链接 `ws2_32.lib` 库。
阅读全文