C语言完成适用于Windows系统的一对一的Socket客户端与服务器程序
时间: 2024-03-06 09:51:21 浏览: 60
C语言实现Socket通信程序
4星 · 用户满意度95%
好的,以下是一个基于C语言实现的适用于Windows系统的一对一Socket客户端与服务器程序:
服务器端代码:
```
#include <stdio.h>
#include <winsock2.h>
#pragma comment(lib, "ws2_32.lib")
#define PORT 8888
int main(int argc, char *argv[]) {
WSADATA wsa;
SOCKET server_socket, new_socket;
struct sockaddr_in server, client;
int client_len = sizeof(client);
char buffer[1024] = {0};
char *hello = "Hello from server";
// 初始化Winsock
if (WSAStartup(MAKEWORD(2, 2), &wsa) != 0) {
printf("WSAStartup failed. Error Code : %d", WSAGetLastError());
return 1;
}
// 创建socket
if ((server_socket = socket(AF_INET, SOCK_STREAM, 0)) == INVALID_SOCKET) {
printf("Could not create socket : %d", WSAGetLastError());
}
// 设置服务器地址和端口号
server.sin_family = AF_INET;
server.sin_addr.s_addr = INADDR_ANY;
server.sin_port = htons(PORT);
// 绑定socket到指定端口
if (bind(server_socket, (struct sockaddr *)&server, sizeof(server)) == SOCKET_ERROR) {
printf("Bind failed with error code : %d", WSAGetLastError());
}
// 监听socket
listen(server_socket, 3);
// 接收客户端连接
new_socket = accept(server_socket, (struct sockaddr *)&client, &client_len);
if (new_socket == INVALID_SOCKET) {
printf("Accept failed with error code : %d", WSAGetLastError());
}
// 从客户端接收消息
recv(new_socket, buffer, 1024, 0);
printf("Client: %s\n", buffer);
// 向客户端发送消息
send(new_socket, hello, strlen(hello), 0);
printf("Hello message sent\n");
// 关闭socket
closesocket(new_socket);
closesocket(server_socket);
// 清理Winsock
WSACleanup();
return 0;
}
```
客户端代码:
```
#include <stdio.h>
#include <winsock2.h>
#pragma comment(lib, "ws2_32.lib")
#define PORT 8888
int main(int argc, char *argv[]) {
WSADATA wsa;
SOCKET client_socket;
struct sockaddr_in server;
char *hello = "Hello from client";
char buffer[1024] = {0};
// 初始化Winsock
if (WSAStartup(MAKEWORD(2, 2), &wsa) != 0) {
printf("WSAStartup failed. Error Code : %d", WSAGetLastError());
return 1;
}
// 创建socket
if ((client_socket = socket(AF_INET, SOCK_STREAM, 0)) == INVALID_SOCKET) {
printf("Could not create socket : %d", WSAGetLastError());
}
// 设置服务器地址和端口号
server.sin_family = AF_INET;
server.sin_addr.s_addr = inet_addr("127.0.0.1");
server.sin_port = htons(PORT);
// 连接服务器
if (connect(client_socket, (struct sockaddr *)&server, sizeof(server)) < 0) {
printf("Connect failed with error code : %d", WSAGetLastError());
return 1;
}
// 向服务器发送消息
send(client_socket, hello, strlen(hello), 0);
printf("Hello message sent\n");
// 从服务器接收消息
recv(client_socket, buffer, 1024, 0);
printf("Server: %s\n", buffer);
// 关闭socket
closesocket(client_socket);
// 清理Winsock
WSACleanup();
return 0;
}
```
这个例子中,服务器端会绑定到本地8888端口,监听客户端的连接。客户端会连接到服务器,并向服务器发送一条消息,然后等待服务器的响应。
希望这个例子对您有所帮助!
阅读全文