首页 > 解决方案 > Unity 从 Android 手机到 PC 的 TCP IP 连接问题(已解决)

问题描述

问题解决了。- 我只需要更改手机的 IP 设置。之后它起作用了! -

我使用 Unity 创建了一个简单的应用程序,其中包含一个按钮和一个 InputField,该应用程序使用 TCP 连接,将输入框中写入的字符串发送到作为服务器运行的 C# 控制台应用程序。

当我在同一台 PC 上使用这两个应用程序时,一切正常,但是当我在手机上安装 apk 文件时,它不起作用。PC和Phone都连接到同一个路由器,我也关闭了防火墙。这不是我第一次在 C# 应用程序上使用 Unity 或 tcp 连接,但这是我第一次一起使用它们。有没有人有同样的问题?你是怎么解决的?我很感激任何帮助。从现在开始感谢大家!

该应用程序看起来像这个应用程序图像

Unity 上的客户端脚本

            
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Linq;
using System.Text;
using System.Threading.Tasks; 
using System.IO;
using System.Threading;
using System.Net;
using System.Net.Sockets;
using System;
public class Client : MonoBehaviour
{
    private TcpClient tcpClient;

    public async Task Initialize(string ip, int port)
    {
        try
        {
            tcpClient = new TcpClient();
            await tcpClient.ConnectAsync(ip, port);
        }
        catch { }
    }

    public void Disconnect()
    {
        if (tcpClient.Connected)
            tcpClient.Close();
    }

    public bool Connected()
    {
        if (tcpClient != null)
            if (tcpClient.Connected)
                return true;

        return false;
    }

    public async Task Read()
    {
        var buffer = new byte[4096];
        var ns = tcpClient.GetStream();
        MemoryStream ms = new MemoryStream();
        while (true)
        {
            var bytesRead = await ns.ReadAsync(buffer, 0, buffer.Length);
            if (bytesRead <= 0) break; // Stream was closed
            ms.Write(buffer, 0, bytesRead);
            ms.Seek(0, SeekOrigin.Begin);
        }
        Debug.Log("connection closed");
    }


    public void BeginSend(string msg)
    {
        try
        {
            var bytes = Encoding.ASCII.GetBytes(msg + "\n");
            var ns = tcpClient.GetStream();
            ns.BeginWrite(bytes, 0, bytes.Length, EndSend, bytes);
        }
        catch { }
    }

    public void EndSend(IAsyncResult result)
    {
        var bytes = (byte[])result.AsyncState;
    }
}

TCP 服务器 C# 控制台应用程序 -


using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Linq;
using System.Text;
using System.Threading.Tasks; 
using System.IO;
using System.Threading;
using System.Net;
using System.Net.Sockets;
using System;


public class Client : MonoBehaviour
{
    private TcpClient tcpClient;

    public async Task Initialize(string ip, int port)
    {
        try
        {
            tcpClient = new TcpClient();
            await tcpClient.ConnectAsync(ip, port);
        }
        catch { }
    }

    public void Disconnect()
    {
        if (tcpClient.Connected)
            tcpClient.Close();
    }

    public bool Connected()
    {
        if (tcpClient != null)
            if (tcpClient.Connected)
                return true;

        return false;
    }

    public async Task Read()
    {
        var buffer = new byte[4096];
        var ns = tcpClient.GetStream();
        MemoryStream ms = new MemoryStream();
        while (true)
        {
            var bytesRead = await ns.ReadAsync(buffer, 0, buffer.Length);
            if (bytesRead <= 0) break; // Stream was closed
            ms.Write(buffer, 0, bytesRead);
            ms.Seek(0, SeekOrigin.Begin);
        }
        Debug.Log("connection closed");
    }


    public void BeginSend(string msg)
    {
        try
        {
            var bytes = Encoding.ASCII.GetBytes(msg + "\n");
            var ns = tcpClient.GetStream();
            ns.BeginWrite(bytes, 0, bytes.Length, EndSend, bytes);
        }
        catch { }
    }

    public void EndSend(IAsyncResult result)
    {
        var bytes = (byte[])result.AsyncState;
    }
}

以及控制 UI 和 TCP 连接的 UIController 脚本

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
using System;
using System.IO;
using System.Net.Sockets;
using System.Text;




public class UIControl : MonoBehaviour
{
    //objects
    public Text textDeneme;

    private static byte[] MessageToByteArray(string message, Encoding encoding)
    {
        var byteCount = encoding.GetByteCount(message);
        if (byteCount > byte.MaxValue)
            throw new ArgumentException("Message size is greater than 255 bytes in the provided encoding");
        var byteArray = new byte[byteCount + 1];
        byteArray[0] = (byte)byteCount;
        encoding.GetBytes(message, 0, message.Length, byteArray, 1);
        return byteArray;
    }

    
    public void connectBtn()
    {

        string message = textDeneme.text;
        var byteArray = MessageToByteArray(message, Encoding.ASCII);
        using (var tcpClient = new TcpClient())
        {
            tcpClient.Connect("192.168.1.133", 5000);
            using (var networkStream = tcpClient.GetStream())
            using (var bufferedStream = new BufferedStream(networkStream))
            {
                bufferedStream.Write(byteArray, 0, byteArray.Length);
            }
        }
    } 
}

标签: androidunity3dtcpconnectionip

解决方案


推荐阅读