使用C语言创建一个TCP socket服务,等待连接后进行交互
时间: 2024-01-02 21:02:37 浏览: 142
好的,以下是使用C语言创建一个TCP socket服务,等待连接后进行交互的基本步骤:
1. 包含头文件
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
```
2. 创建socket
```c
int server_socket = socket(AF_INET, SOCK_STREAM, 0);
if (server_socket == -1) {
printf("创建socket失败\n");
exit(1);
}
```
3. 绑定地址和端口号
```c
struct sockaddr_in server_addr;
memset(&server_addr, 0, sizeof(server_addr));
server_addr.sin_family = AF_INET;
server_addr.sin_addr.s_addr = htonl(INADDR_ANY);
server_addr.sin_port = htons(8888); // 端口号
int bind_result = bind(server_socket, (struct sockaddr*)&server_addr, sizeof(server_addr));
if (bind_result == -1) {
printf("绑定地址和端口号失败\n");
exit(1);
}
```
4. 监听连接请求
```c
int listen_result = listen(server_socket, 10); // 最多连接10个client
if (listen_result == -1) {
printf("监听连接请求失败\n");
exit(1);
}
```
5. 接受连接请求
```c
struct sockaddr_in client_addr;
socklen_t client_addr_len = sizeof(client_addr);
int client_socket = accept(server_socket, (struct sockaddr*)&client_addr, &client_addr_len);
if (client_socket == -1) {
printf("接受连接请求失败\n");
exit(1);
}
char client_ip[16];
inet_ntop(AF_INET, &client_addr.sin_addr, client_ip, sizeof(client_ip));
printf("客户端 %s:%d 已连接\n", client_ip, ntohs(client_addr.sin_port));
```
6. 与客户端进行交互
```c
char buffer[1024];
while (1) {
memset(buffer, 0, sizeof(buffer));
int recv_result = recv(client_socket, buffer, sizeof(buffer), 0);
if (recv_result <= 0) {
printf("客户端 %s:%d 已断开连接\n", client_ip, ntohs(client_addr.sin_port));
break;
}
printf("客户端 %s:%d 发来消息:%s\n", client_ip, ntohs(client_addr.sin_port), buffer);
char reply[] = "服务器已收到消息";
int send_result = send(client_socket, reply, sizeof(reply), 0);
if (send_result == -1) {
printf("发送消息失败\n");
exit(1);
}
}
```
7. 关闭socket
```c
close(client_socket);
close(server_socket);
```
以上就是使用C语言创建一个TCP socket服务,等待连接后进行交互的基本步骤。
阅读全文