socket通信C++示例
时间: 2023-07-08 14:43:51 浏览: 151
下面是一个简单的使用Socket进行通信的C++示例:
```c++
#include <iostream>
#include <cstring>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
using namespace std;
const int PORT = 8080;
int main() {
int server_fd, new_socket;
struct sockaddr_in address;
int opt = 1;
int addrlen = sizeof(address);
char buffer[1024] = {0};
const char *hello = "Hello from server";
// 创建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(PORT);
// 绑定socket到指定端口
if (bind(server_fd, (struct sockaddr *)&address, sizeof(address))<0) {
perror("bind failed");
exit(EXIT_FAILURE);
}
// 监听socket
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);
}
// 从客户端接收消息
int valread;
if ((valread = read(new_socket, buffer, 1024)) == 0) {
cout << "Client disconnected" << endl;
} else {
cout << "Received message: " << buffer << endl;
}
// 向客户端发送消息
send(new_socket, hello, strlen(hello), 0);
cout << "Hello message sent" << endl;
return 0;
}
```
这个示例创建了一个TCP服务器,监听8080端口。当有客户端连接时,服务器将从客户端接收消息,打印消息内容,并向客户端发送“Hello from server”消息。
阅读全文