gpt4 book ai didi

c++ - 如何通过 pthread 发送套接字 ID?

转载 作者:太空狗 更新时间:2023-10-29 22:54:11 35 4
gpt4 key购买 nike

我在树莓派中有一个服务器,并希望允许多线程。服务器正在工作。客户端在windows中。我相信我需要通过 pthread_create 发送套接字 ID,但还没有找到方法。我还需要发送什么吗?最好的方法是什么?

我搜索了互联网,包括 stackoverflow,并尝试了一些解决方案,但它们没有用。

const int PORT = 12000;
TCPServer tcp;
pthread_t my_thread[MAXCLIENTQUEUE];
int clientID = 0;

int main()
{

tcp.setup(PORT);

int clientQueueSize = 0, threadJoin = 0;
void *res;

do {
socklen_t sosize = sizeof(tcp.clientAddress);
//realizar o accept
tcp.newsockfd[clientQueueSize] = accept(tcp.sockfd, (struct sockaddr*) & tcp.clientAddress, &sosize);
if (tcp.newsockfd[clientQueueSize] == -1)
{
cout << "Error accepting -> " << tcp.newsockfd[clientQueueSize] << endl;
tcp.detach();
}
cout << ">- accept: " << strerror(errno) << " / codigo: " << tcp.newsockfd[clientQueueSize] << " - Endereco: " << inet_ntoa(tcp.clientAddress.sin_addr) << endl;
clientID++;
cout << ">>> client accepted" << " | Client ID: " << clientID << endl;
// criar threads
int ret = pthread_create(&my_thread[clientQueueSize], NULL, messenger, &tcp.newsockfd[clientQueueSize]);
cout << ">- pthread: " << strerror(errno) << " / codigo: " << ret << endl;
if (ret != 0) {
cout << "Error: pthread_create() failed\n" << "thread_n " << my_thread[clientQueueSize] << endl;
exit(EXIT_FAILURE);
}
cout << "thread n " << my_thread[clientQueueSize] << endl;
clientQueueSize++;
}
while (clientQueueSize < MAXCLIENTQUEUE);

pthread_exit(NULL);

return 0;
}

服务器接受多个连接,但只向第一个客户端发送消息,其他客户端连接成功,但从不接收消息。我希望服务器能够向所有客户端发送消息。

最佳答案

您必须为所有套接字创建线程。或者,使用依赖于 Windows 的异步选择方法。

附言忘记 pthreads 并使用标准 std::thread .

   map<SOCKET,std::string> clients;
void newclient(SOCKET x)
{
for(;;)
{
int r = recv(x,...);
if (r == 0 || r == -1)
break;
}
// remove it from clients, ensure proper synchronization

}

void server()
{
SOCKET x = socket(...);
bind(x,...);
listen(x,...);
for(;;)
{
auto s = accept(x,...);
if (s == INVALID_SOCKET)
break;

// save to a map, for example, after ensuring sync with a mutex and a lock guard

m[s] = "some_id";

std::thread t(newclient,s);
s.detach();
}
}

int main() //
{
// WSAStartup and other init

std::thread t(server);
t.detach();

// Message Loop or other GUI

}

关于c++ - 如何通过 pthread 发送套接字 ID?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56901768/

35 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com