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

How can I send socket id through pthread?

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

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

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-depended 异步 select 方法。

P.S。忘记 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

   }