服务端
server.cpp
#include <iostream>
#include <sys/socket.h>
#include <netinet/in.h>
#include <unistd.h>
#include <cstring>
int main() {
int server_fd, new_socket;
struct sockaddr_in address;
int opt = 1;
int addrlen = sizeof(address);
char buffer[1024] = {0};
// 创建 socket
if ((server_fd = socket(AF_INET, SOCK_STREAM, 0)) == 0) {
perror("socket failed");
exit(EXIT_FAILURE);
}
// 绑定 socket
if (setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR | SO_REUSEPORT, &opt, sizeof(opt))) {
perror("setsockopt");
exit(EXIT_FAILURE);
}
address.sin_family = AF_INET;
address.sin_addr.s_addr = INADDR_ANY;
address.sin_port = htons(8080);
if (bind(server_fd, (struct sockaddr *)&address, sizeof(address)) < 0) {
perror("bind failed");
exit(EXIT_FAILURE);
}
// 监听
if (listen(server_fd, 3) < 0) {
perror("listen");
exit(EXIT_FAILURE);
}
// 接受连接
if ((new_socket = accept(server_fd, (struct sockaddr *)&address, (socklen_t*)&addrlen)) < 0) {
perror("accept");
exit(EXIT_FAILURE);
}
// 读取来自客户端的数据
read(new_socket, buffer, 1024);
std::cout << "Message from client: " << buffer << std::endl;
// 发送回应
const char *response = "Hello from server";
send(new_socket, response, strlen(response), 0);
// 关闭 socket
close(new_socket);
close(server_fd);
return 0;
}
客户端
client.cpp
#include <iostream>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <cstring>
int main() {
int sock = 0;
struct sockaddr_in serv_addr;
const char *message = "Hello from client";
char buffer[1024] = {0};
// 创建 socket
if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
std::cout << "Socket creation error" << std::endl;
return -1;
}
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(8080);
// 转换 IP 地址
if(inet_pton(AF_INET, "127.0.0.1", &serv_addr.sin_addr) <= 0) {
std::cout << "Invalid address/ Address not supported" << std::endl;
return -1;
}
// 连接到服务器
if (connect(sock, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0) {
std::cout << "Connection Failed" << std::endl;
return -1;
}
// 发送消息
send(sock, message, strlen(message), 0);
// 读取服务器的回应
read(sock, buffer, 1024);
std::cout << "Message from server: " << buffer << std::endl;
// 关闭 socket
close(sock);
return 0;
}
说明
- 服务器:
创建一个 socket 并绑定到端口 8080。
监听连接并接受客户端请求。
接收消息并发送回应。 - 客户端:
创建一个 socket 并连接到服务器的 127.0.0.1:8080。
发送消息并接收回应。 - 编译:
使用 g++ 编译:g++ server.cpp -o server 和 g++ client.cpp -o client。 - 运行:
先运行服务器:./server。
然后运行客户端:./client。
运行
$./server
Message from client: Hello from client
$./client
Message from server: Hello from server