socket 通信 C++实现代码
时间: 2023-11-01 15:06:42 浏览: 161
以下是一个简单的 C++ Socket 通信代码示例:
服务端:
```cpp
#include <iostream>
#include <cstring>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
using namespace std;
int main(int argc, char *argv[]) {
int server_fd, client_fd;
struct sockaddr_in server_addr, client_addr;
char buffer[1024] = {0};
// 创建 socket
if ((server_fd = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
perror("socket failed");
exit(EXIT_FAILURE);
}
// 设置服务器地址和端口
server_addr.sin_family = AF_INET;
server_addr.sin_addr.s_addr = INADDR_ANY;
server_addr.sin_port = htons(8000);
// 绑定地址和端口
if (bind(server_fd, (struct sockaddr*)&server_addr, sizeof(server_addr)) == -1) {
perror("bind failed");
exit(EXIT_FAILURE);
}
// 开始监听客户端连接
if (listen(server_fd, 5) == -1) {
perror("listen failed");
exit(EXIT_FAILURE);
}
socklen_t client_addr_len = sizeof(client_addr);
// 等待客户端连接
if ((client_fd = accept(server_fd, (struct sockaddr*)&client_addr, &client_addr_len)) == -1) {
perror("accept failed");
exit(EXIT_FAILURE);
}
// 接收客户端消息
int valread = read(client_fd, buffer, 1024);
cout << "Received: " << buffer << endl;
// 发送消息给客户端
const char* message = "Hello from server";
send(client_fd, message, strlen(message), 0);
return 0;
}
```
客户端:
```cpp
#include <iostream>
#include <cstring>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
using namespace std;
int main(int argc, char *argv[]) {
int client_fd;
struct sockaddr_in server_addr;
char buffer[1024] = {0};
// 创建 socket
if ((client_fd = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
perror("socket failed");
exit(EXIT_FAILURE);
}
// 设置服务器地址和端口
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(8000);
// 转换 IP 地址
if (inet_pton(AF_INET, "127.0.0.1", &server_addr.sin_addr) <= 0) {
perror("inet_pton failed");
exit(EXIT_FAILURE);
}
// 连接服务器
if (connect(client_fd, (struct sockaddr*)&server_addr, sizeof(server_addr)) == -1) {
perror("connect failed");
exit(EXIT_FAILURE);
}
// 发送消息给服务器
const char* message = "Hello from client";
send(client_fd, message, strlen(message), 0);
// 接收服务器消息
int valread = read(client_fd, buffer, 1024);
cout << "Received: " << buffer << endl;
return 0;
}
```
阅读全文