写一份C++的代码实现两个进程之间用socket通信
时间: 2023-11-28 19:47:30 浏览: 132
以下是一个简单的 C++ 代码示例,可以实现两个进程之间使用 socket 进行通信。此代码使用 TCP 协议进行通信,并使用 POSIX socket API。
```
#include <iostream>
#include <unistd.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <cstring>
using namespace std;
int main() {
int server_socket, client_socket;
struct sockaddr_in server_address, client_address;
char buffer[1024];
// 创建 socket
server_socket = socket(AF_INET, SOCK_STREAM, 0);
// 设置服务器地址
memset(&server_address, 0, sizeof(server_address));
server_address.sin_family = AF_INET;
server_address.sin_addr.s_addr = htonl(INADDR_ANY);
server_address.sin_port = htons(12345);
// 绑定 socket
bind(server_socket, (struct sockaddr*)&server_address, sizeof(server_address));
// 监听 socket
listen(server_socket, 5);
// 等待客户端连接
socklen_t client_address_len = sizeof(client_address);
client_socket = accept(server_socket, (struct sockaddr*)&client_address, &client_address_len);
// 接收客户端消息并发送回复
while (true) {
int length = recv(client_socket, buffer, sizeof(buffer), 0);
if (length <= 0) {
break;
}
buffer[length] = '\0';
cout << "Received message: " << buffer << endl;
send(client_socket, buffer, length, 0);
}
// 关闭 socket
close(client_socket);
close(server_socket);
return 0;
}
```
以上代码创建了一个服务器 socket,将其绑定到本地地址和端口上,并开始监听。当客户端连接时,服务器将接受客户端发送的消息,并将其发送回去。您需要再创建一个客户端 socket,通过它与服务器建立连接并进行通信。
阅读全文