linux编写一个服务器与客户端的通信例程,基于tcp的通信 centos6
时间: 2023-03-22 20:04:06 浏览: 113
很高兴为您提供帮助。下面是一个基于TCP协议的Linux服务器与客户端通信的例程:
服务器端:
1. 创建套接字:
```
int server_socket = socket(AF_INET, SOCK_STREAM, 0);
```
2. 绑定IP地址和端口号:
```
struct sockaddr_in server_addr;
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(port); // port为服务器监听的端口号
server_addr.sin_addr.s_addr = htonl(INADDR_ANY);
bind(server_socket, (struct sockaddr*)&server_addr, sizeof(server_addr));
```
3. 监听客户端连接请求:
```
listen(server_socket, 5); // 5为等待连接队列的最大长度
```
4. 接受客户端连接请求:
```
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);
```
5. 接收客户端发送的数据:
```
char buffer[1024];
int len = recv(client_socket, buffer, sizeof(buffer), 0);
```
6. 发送数据给客户端:
```
char* message = "Hello, client!";
send(client_socket, message, strlen(message), 0);
```
7. 关闭套接字:
```
close(client_socket);
close(server_socket);
```
客户端:
1. 创建套接字:
```
int client_socket = socket(AF_INET, SOCK_STREAM, 0);
```
2. 连接服务器:
```
struct sockaddr_in server_addr;
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(port); // port为服务器监听的端口号
server_addr.sin_addr.s_addr = inet_addr(server_ip); // server_ip为服务器的IP地址
connect(client_socket, (struct sockaddr*)&server_addr, sizeof(server_addr));
```
3. 发送数据给服务器:
```
char* message = "Hello, server!";
send(client_socket, message, strlen(message), 0);
```
4. 接收服务器发送的数据:
```
char buffer[1024];
int len = recv(client_socket, buffer, sizeof(buffer), 0);
```
5. 关闭套接字:
```
close(client_socket);
```
以上是一个简单的基于TCP协议的Linux服务器与客户端通信的例程,希望对您有所帮助。
阅读全文