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

时间:2019-04-01 09:36:42

标签: 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 = 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上运行的服务器。我怎样才能解决这个问题?

1 个答案:

答案 0 :(得分:2)

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

client.Connect(IPAddress.Loopback, port); 

应该被注释掉,而

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

恕我直言是正确的代码行。

我目前无法测试您的代码,我的声誉太低,无法将其发布为评论...对不起。