windows环境下socket客户端服务器通信c代码
时间: 2023-07-15 22:14:54 浏览: 102
以下是一个简单的 Windows 环境下使用 socket 进行客户端和服务器通信的 C 代码示例。
服务器端代码:
```c
#include <stdio.h>
#include <winsock2.h>
#pragma comment(lib, "ws2_32.lib") // 链接 ws2_32.lib 库
int main() {
WSADATA wsaData;
SOCKET serverSocket, clientSocket;
SOCKADDR_IN serverAddr, clientAddr;
int clientAddrLen = sizeof(clientAddr);
char buffer[1024] = {0};
// 初始化 Winsock
int iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
if (iResult != 0) {
printf("WSAStartup failed: %d\n", iResult);
return 1;
}
// 创建套接字
serverSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (serverSocket == INVALID_SOCKET) {
printf("socket failed: %ld\n", WSAGetLastError());
WSACleanup();
return 1;
}
// 绑定套接字到本地端口
serverAddr.sin_family = AF_INET;
serverAddr.sin_addr.s_addr = htonl(INADDR_ANY);
serverAddr.sin_port = htons(8888);
if (bind(serverSocket, (SOCKADDR*)&serverAddr, sizeof(serverAddr)) == SOCKET_ERROR) {
printf("bind failed: %d\n", WSAGetLastError());
closesocket(serverSocket);
WSACleanup();
return 1;
}
// 监听客户端连接请求
if (listen(serverSocket, 5) == SOCKET_ERROR) {
printf("listen failed: %d\n", WSAGetLastError());
closesocket(serverSocket);
WSACleanup();
return 1;
}
// 等待客户端连接
printf("等待客户端连接...\n");
clientSocket = accept(serverSocket, (SOCKADDR*)&clientAddr, &clientAddrLen);
if (clientSocket == INVALID_SOCKET) {
printf("accept failed: %d\n", WSAGetLastError());
closesocket(serverSocket);
WSACleanup();
return 1;
}
// 接收客户端消息并回复
while (1) {
int bytesReceived = recv(clientSocket, buffer, sizeof(buffer), 0);
if (bytesReceived > 0) {
printf("接收到客户端消息: %s\n", buffer);
send(clientSocket, buffer, bytesReceived, 0);
}
}
// 关闭套接字
closesocket(serverSocket);
WSACleanup();
return 0;
}
```
客户端代码:
```c
#include <stdio.h>
#include <winsock2.h>
#pragma comment(lib, "ws2_32.lib") // 链接 ws2_32.lib 库
int main() {
WSADATA wsaData;
SOCKET clientSocket;
SOCKADDR_IN serverAddr;
char buffer[1024] = {0};
// 初始化 Winsock
int iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
if (iResult != 0) {
printf("WSAStartup failed: %d\n", iResult);
return 1;
}
// 创建套接字
clientSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (clientSocket == INVALID_SOCKET) {
printf("socket failed: %ld\n", WSAGetLastError());
WSACleanup();
return 1;
}
// 连接到服务器
serverAddr.sin_family = AF_INET;
serverAddr.sin_addr.s_addr = inet_addr("127.0.0.1");
serverAddr.sin_port = htons(8888);
if (connect(clientSocket, (SOCKADDR*)&serverAddr, sizeof(serverAddr)) == SOCKET_ERROR) {
printf("connect failed: %d\n", WSAGetLastError());
closesocket(clientSocket);
WSACleanup();
return 1;
}
// 发送消息并等待回复
while (1) {
printf("请输入消息:");
gets(buffer);
send(clientSocket, buffer, strlen(buffer), 0);
int bytesReceived = recv(clientSocket, buffer, sizeof(buffer), 0);
if (bytesReceived > 0) {
buffer[bytesReceived] = '\0';
printf("收到服务器回复:%s\n", buffer);
}
}
// 关闭套接字
closesocket(clientSocket);
WSACleanup();
return 0;
}
```
注意:以上代码仅供参考,实际应用中需要进行错误处理和安全性校验。
阅读全文