正在 Android 和 Desktop 之间建立 TCP 连接

Establishing a TCP connection between Android and Desktop

我正在尝试在我的移动设备和台式机之间建立套接字连接。移动设备(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 () 
    {
    }
}

客户端代码如下

public class Receiver : MonoBehaviour
{
    public bool enableLog = false;
    const int port = 8010;
    public string IP = "192.168.122.24";
    TcpClient client;

    private bool stop = false;

    //This must be the-same with SEND_COUNT on the server
    const int SEND_RECEIVE_COUNT = 15;

    // Use this for initialization
    void Start()
    {
        Application.runInBackground = true;

        tex = new Texture2D(0, 0);
        client = new TcpClient();

        //Connect to server from another Thread
        Loom.RunAsync(() =>
        {
            LOGWARNING("Connecting to server...");
            // if on desktop
            client.Connect(IPAddress.Loopback, port);
            // if using the IPAD
            //client.Connect(IPAddress.Parse(IP), port);
            Debug.Log("Connected");

        });
    }

    void Update()
    {
    }

    void OnApplicationQuit()
    {
        LOGWARNING("OnApplicationQuit");
        stop = true;

        if (client != null)
        {
            client.Close();
        }
    }
}

但由于某种原因,客户端无法在 Android 上连接到服务器 运行。我怎样才能解决这个问题?

在 TcpClient.Connect(IPEndPoint) 上,您应该指定要连接的设备的 IP。

client.Connect(IPAddress.Loopback, port); 

应该被注释掉,而

//client.Connect(IPAddress.Parse(IP), port);

恕我直言,代码行是否正确。

我目前无法测试您的代码,而且我的声誉太低无法post将此作为评论...抱歉。