【发布时间】:2021-04-30 09:32:14
【问题描述】:
我想在套接字上创建一个多线程服务器。我创建了一个线程,但是我事先不知道会有多少个线程,我不能在循环中启动一个线程,因为有一个暂停
#include <iostream>
#include <sys/socket.h>
#include <netinet/in.h>
#include <cstdio>
#include <cstdlib>
#include <unistd.h>
#include <cstring>
#include <thread>
#define PORT 8000
class ConnectSocket {
public:
explicit ConnectSocket(int socket) {
std::cout << "New connect: " << this << std::endl;
this->buffer = new char[1024];
this->bytes_read = new int;
this->socket = new int;
*(this->socket) = socket;
while (true) {
if (get_content() == -1) {
break;
}
send_content(this->buffer);
std::cout << "content: " << this->buffer << std::endl;
}
close_connection();
}
~ConnectSocket(){
std::cout << "End connect " << this << std::endl;
delete[] this->buffer;
delete this->bytes_read;
delete this->socket;
}
private:
char *buffer;
int *bytes_read;
int *socket;
int get_content() {
if (this->buffer != nullptr && this->socket != nullptr) {
*(this->bytes_read) = recv(*(this->socket), this->buffer, 1024, 0);
if(*(this->bytes_read) <= 0) return -1;
return 0;
} else return -1;
}
int send_content(char *content){
if (this->buffer != nullptr && this->socket != nullptr) {
send(*(this->socket), content, strlen(content), 0);
return 0;
} else return -1;
}
void close_connection() {
close(*(this->socket));
delete this;
}
};
void runConnection(int sock) {
ConnectSocket *connect_socket = new ConnectSocket(sock);
}
int main()
{
int sock, listener;
struct sockaddr_in addr;
listener = socket(AF_INET, SOCK_STREAM, 0);
if(listener < 0)
{
perror("socket");
exit(1);
}
addr.sin_family = AF_INET;
addr.sin_port = htons(PORT);
addr.sin_addr.s_addr = htonl(INADDR_ANY);
if(bind(listener, (struct sockaddr *)&addr, sizeof(addr)) < 0)
{
perror("bind");
exit(2);
}
listen(listener, 1);
while(1)
{
sock = accept(listener, NULL, NULL);
if(sock < 0)
{
perror("accept");
exit(3);
}
std::thread thr(runConnection, sock);
thr.join();
}
return 0;
}
如何让 ConnectSocket 类在每个连接的单独线程中运行? 现在服务器只能处理一个连接
【问题讨论】:
标签: c++ c multithreading sockets