首页 文章

在C#中统一TCP和UDP

提问于
浏览
0

理想情况下,我正在寻找一种方法来在服务器上统一TCP和UDP,并在各个客户端线程下管理这两个连接 . 目前,我想知道是否可以接受TCP连接并从中设置UDP通信 .

这是我理想的设置:

  • 客户端通过TCPClient.connect()在TCP上连接到服务器

  • Server通过TCPListener接受TCP连接

  • 当服务器接受TCP连接时,它还从TCP连接获取IPEndpoint

并使用它来开始UDP通信:

serverUDPSocket.BeginReceiveFrom (byteData, 0, 1024, 
               SocketFlags.None, ref (Endpoint)ThatIPEndpointThatIJustMentioned, 
               new AsyncCallback(client.receiveUDP), 
               (Endpoint)ThatIPEndpointThatIJustMentioned);

^所以这是我遇到一些理论问题的地方 . 根据我的理解,TCP和UDP的 endpoints 格式不同 . 我该如何解决这个问题?我想避免客户端在单独的线程上连接到UDP,然后将这些线程联合在一个管理类下 .

编辑:

这是我试图实现的代码:

//Listening for TCP
TcpClient newclient = listenTCP.AcceptTcpClient(); //Accept the client
Client clientr = new Client(newclient); //Create a new Client class to manage the connection
clientr.actionThread = new Thread(clientr.action); //This thread manages the data flow from the client via the TCP stream
clientr.actionThread.Start(clientr);
EndPoint endPoint = newclient.Client.RemoteEndPoint; //so this is the sketchy part. I am trying to get the endpoint from the TCP connection to set up a UDP "connection". I am unsure about the compatibility as UDP and TCP sockets are different.
UDPSocket.BeginReceiveFrom(new byte[1024],0,1024, SocketFlags.None,ref endPoint, new AsyncCallback(clientr.receiveUDP), null); //the AsyncCallBack is like the manager thread for UDP (same as in TCP)
clients.Add(clientr);

2 回答

  • 0

    在一个应用程序中创建两个侦听器没有问题,即使它们使用不同的协议 . 我想你不会问你是否可以在同一个端口上进行(无论如何都没有意义) .

    但是监听器正在消耗线程,因此如果在应用程序中存在gui或某些进程(例如同时计算),则它需要不同的线程 .

    如果您想在一个线程中执行所有操作,则必须先从第一个侦听器接收消息,然后再设置第二个侦听器 . 不可能同时在一个线程中设置2个侦听器,因为如果您设置第一个侦听器,它将使整个线程等待消息 .

  • 0

    这是因为我从代码级别对UDP缺乏了解 .

    我最终设置了我描述的另一种方法,它将单独接受初始UDP数据包,然后通过比较IP地址将通信(EndPoint Message)指向管理客户端类 .

相关问题