TCPListener and StreamSocket

本秂侑毒 提交于 2021-01-29 10:32:53

问题


I have an odd problem. I'm trying to get a TCP connection going from my local PC to a remote hololens. On PC, I use the standard C# APIs (TCPClient, TCPListener) and on the Hololens I'm forced to use the UWP stuff (StreamSocket, StreamSocketListener).

I have tested the following configurations:

StreamSocket (local PC) <-> StreamSocketListener (Hololens): Working

StreamSocketListener (local PC) <-> StreamSocket (Hololens): Working

TCPClient (local PC) <-> StreamSocketListener (Hololens): Working

TCPClient (local PC) <-> TCPListener (also local client): Working

But!

TCPListener (local PC) <-> StreamSocket (Hololens): Not working!

Even more confusing!

TCPListener (local PC) <-> StreamSocket (as UWP app on local PC): Working! (Even though localhost should be blocked by the UWP API by default)

Is this explicitly prohibited somehow? And is there a way around it? Not sure if I should show code, it's typical, minimal, and copypasted from doc references.

So for some reason my Hololens can't initiate contact to the PC, but the other way around works (StreamSocketListener on Hololens, TCPClient on PC).

There's a related question at

Can't use StreamSocket to connect to a TcpListener

but I'm not testing over localhost. I'm testing between Hololens and the PC.

Here's what the TCPListener usage looks like:

var connectionListener = new TcpListener(localAddress, port);
connectionListener.Start();
connectionListener.BeginAcceptTcpClient(AcceptTCPClient, connectionListener);

//somewhere else
private void AcceptTCPClient(IAsyncResult result)
        {

            var client = connectionListener.EndAcceptTcpClient(result);

            OnConnectEvent(client); //custom callback, registered somewhere outside

            connectionListener.BeginAcceptTcpClient(AcceptTCPClient, connectionListener); //accept next client
        }

And perhaps also relevant, StreamSocket usage:

//this all happens in a separate thread.
var networkSocket = new StreamSocket();

 while (!IsConnected)
            {
                try
                {
                    await networkSocket.ConnectAsync(new HostName("192.168.0.101"), "7777");
                    //do stuff with socket here
                }
                catch (Exception e)
                {
                    //errorhandling here
                }
            }

I should note that I have separate TCPListeners for each local network address.


回答1:


Same problem resolved by configuring TcpListener to listen to any IP address.

IPEndPoint ipEndPoint = new IPEndPoint(IPAddress.Any, ConnectionPort);
networkListener = new TcpListener (ipEndPoint);
networkListener.Start (10);


来源:https://stackoverflow.com/questions/50042058/tcplistener-and-streamsocket

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!