服务器 linux socket c++ 编程代码
时间: 2023-09-12 17:10:03 浏览: 124
以下是一个简单的 Linux Socket 编程的 C++ 代码示例:
```c++
#include <iostream>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <string.h>
#include <thread>
#define PORT 8080
void handle_client(int socket_fd) {
char buffer[1024] = {0};
int valread = read(socket_fd, buffer, 1024);
std::cout << "Received message: " << buffer << std::endl;
send(socket_fd, "Server received your message!", strlen("Server received your message!"), 0);
close(socket_fd);
}
int main(int argc, char const *argv[]) {
int server_fd;
struct sockaddr_in address;
int opt = 1;
int addrlen = sizeof(address);
// Creating socket file descriptor
if ((server_fd = socket(AF_INET, SOCK_STREAM, 0)) == 0) {
perror("socket failed");
exit(EXIT_FAILURE);
}
// Forcefully attaching socket to the port 8080
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);
// Binding socket to the specified address and port
if (bind(server_fd, (struct sockaddr *)&address, sizeof(address)) < 0) {
perror("bind failed");
exit(EXIT_FAILURE);
}
// Listening for incoming connections
if (listen(server_fd, 3) < 0) {
perror("listen");
exit(EXIT_FAILURE);
}
std::cout << "Server is running on port " << PORT << std::endl;
while (true) {
// Accepting incoming connections
int socket_fd = accept(server_fd, (struct sockaddr *)&address, (socklen_t*)&addrlen);
if (socket_fd < 0) {
perror("accept");
exit(EXIT_FAILURE);
}
std::thread t(handle_client, socket_fd);
t.detach();
}
return 0;
}
```
以上代码创建了一个简单的服务器,它监听 8080 端口,并在收到客户端的连接请求后处理客户端发送的消息,并向客户端发送回复消息。可以通过编译并运行该代码,然后使用 telnet 或其他客户端工具连接到该服务器进行测试。
阅读全文