C# 在Android和桌面之间建立TCP连接

C# 在Android和桌面之间建立TCP连接,c#,unity3d,tcpclient,tcplistener,android-unity-plugin,C#,Unity3d,Tcpclient,Tcplistener,Android Unity Plugin,我正在尝试在我的移动设备和桌面之间建立套接字连接。当桌面是客户端机器时,移动设备android将充当服务器 下面是我的服务器代码 public class PhoneCamera : MonoBehaviour { private TcpListener listner; private const int port = 8010; private bool stop = false; private List<TcpClient> clients

我正在尝试在我的移动设备和桌面之间建立套接字连接。当桌面是客户端机器时,移动设备android将充当服务器

下面是我的服务器代码

public class PhoneCamera : MonoBehaviour 
{
    private TcpListener listner;
    private const int port = 8010;
    private bool stop = false;

    private List<TcpClient> clients = new List<TcpClient>();

    public void Start ()
    {
       Application.runInBackground = true;
       initAndWaitForWebCamTexture();
    }

    void initAndWaitForWebCamTexture()
    {
        listner = new TcpListener(IPAddress.Any, port);

        listner.Start();
        //Start sending coroutine
        StartCoroutine(senderCOR());
    }

    WaitForEndOfFrame endOfFrame = new WaitForEndOfFrame();

    IEnumerator senderCOR()
    {
        bool isConnected = false;
        TcpClient client = null;
        NetworkStream stream = null;

        // Wait for client to connect in another Thread 
        Loom.RunAsync(() =>
        {
            while (!stop)
            {
                // Wait for client connection
                client = listner.AcceptTcpClient();
                // We are connected
                clients.Add(client);

                isConnected = true;
                stream = client.GetStream();
            }
        });

        //Wait until client has connected
        while (!isConnected)
        {
            yield return null;
        }

        LOG("Connected!");
    }

    void LOG(string messsage)
    {
        Debug.Log(messsage);
    }

    private void Update () 
    {
    }
}

但由于某些原因,客户端无法连接到运行在Android上的服务器。如何才能解决此问题?

在TcpClient.ConnectIPEndPoint上,您应该指定要连接到的设备的ip

client.Connect(IPAddress.Loopback, port); 
应该注释掉,而

//client.Connect(IPAddress.Parse(IP), port);
IMHO是正确的代码行


我目前无法测试您的代码,而且我的声誉太低,无法将此作为评论发布……对不起。

android在wifi上和桌面上一样吗?安卓192.168.122.24的IP是否正常?如果没有异常,请首先检查网络连接是否正常。你可以从任何一台设备ping这些端口吗?是的,它是相同的wifi,ip当然是192.168.122.24你在尝试连接时是否遇到任何错误/异常?我尝试ping,我可以ping它
//client.Connect(IPAddress.Parse(IP), port);