使用 C++ 在服务器上同时收听 UDP 和 TCP

listen to UDP and TCP at same time on server using C++

我正在尝试编写一个套接字和客户端程序,这样服务器应该同时监听两个连接。

例如,当我启动服务器时,它会监听 UDP 端口和 TCP 端口,每当 UDP 客户端发送消息时,它必须处理它,当 TCP 客户端发送消息时,它必须处理它。

我尝试使用 pthreads 但无法实现我想要的。

以下是 C++ 代码中的详细信息

以下函数将被相应的 pthreads 调用

void *TCP(void *ptr)
{
    char tcp[MAXDATASIZE];
    cout << "\nEnter TCP port number\n";
    cin >> tcp;
    Server tcpServer(tcp,1);
    tcpServer.testbind(1);
    pthread_exit(NULL);

}

void *UDP(void *ptr)
{
    char udp[MAXDATASIZE];
    cout << "\nEnter UDP port number\n";
    cin >> udp;
    Server udpServer(udp,2);
    udpServer.testDNS(2);
    pthread_exit(NULL);

}

主程序

int main(int c, char *argv[])
{
  char tcp[MAX],udp[MAX];
  int choice,choice1;
  void *i;
  pthread_t tcpThread,udpThread;
  int tcpThreadCheck,udpThreadCheck;
  pthread_attr_t attr;
  pthread_attr_init(&attr);
  pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
  choice1 = pthread_create(&tcpThread,NULL,testTCP,i);
  choice = pthread_create(&udpThread,NULL,testUDP,i);
  if(choice <0) cout <<" Main tcp thread failed"<<endl;
  if(choice1 <0) cout <<" Main udp thread failed"<<endl;

  pthread_attr_destroy(&attr);
  pthread_exit(NULL);
}

每当我尝试 运行 这个服务器程序时,我都会得到 "Enter TCP Port number " 和 "Enter UDP port number" 模拟或以杂乱无章的方式。我希望 bot tcpServer 和 udpServer 独立 运行 并处理来自各自客户端的传入数据。

任何人都可以在这里帮助我,如何实现这一点。有例子吗?

提前致谢。

你启动了两个线程,它们同时执行。当然,他们会同时打印他们的东西,他们也会同时读取 std::cin 和风景效果。我建议你在启动线程之前从用户那里获取你的端口,而不是向线程提供已知的端口。

你的代码还有其他问题——你不应该从 main() 中 pthread_exit,并且在你的情况下你不需要 pthread_attr——你可以简单地提供 NULL,默认值正好你在供应什么。