请你用c++ 写一个建立网络通信的 程序
时间: 2023-02-27 07:52:44 浏览: 131
C++网络通信
好的,以下是一个使用 C 语言实现的简单的网络通信程序的例子:
```
#include <stdio.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <string.h>
#define PORT 8080
#define MAX_BUF_LEN 1024
int main(int argc, char const *argv[]) {
int server_socket, client_socket;
struct sockaddr_in server_address;
char buffer[MAX_BUF_LEN];
// 创建 socket
server_socket = socket(AF_INET, SOCK_STREAM, 0);
if (server_socket < 0) {
printf("创建 socket 失败\n");
return 1;
}
// 填写服务器信息
server_address.sin_family = AF_INET;
server_address.sin_port = htons(PORT);
server_address.sin_addr.s_addr = htonl(INADDR_ANY);
// 绑定 socket 到服务器信息
if (bind(server_socket, (struct sockaddr *)&server_address, sizeof(server_address)) < 0) {
printf("绑定 socket 失败\n");
return 1;
}
// 监听 socket
if (listen(server_socket, 10) < 0) {
printf("监听 socket 失败\n");
return 1;
}
// 接收客户端连接请求
printf("等待客户端连接...\n");
client_socket = accept(server_socket, NULL, NULL);
if (client_socket < 0) {
printf("接收客户端连接请求失败\n");
return 1;
}
// 接收客户端的数据
int bytes_received = recv(client_socket, buffer, MAX_BUF_LEN, 0);
if (bytes_received < 0) {
printf("接收客户端数据失败\n");
return 1;
}
// 向客户端发送数据
int bytes_sent = send(client_socket, buffer, bytes_received, 0);
if (bytes_sent < 0) {
printf("向客户端发送数据失败\n");
return 1;
}
printf("已经成功接收
阅读全文