【发布时间】:2020-03-17 03:29:49
【问题描述】:
我有一个 tcp 连接程序。有客户端和服务器端。客户端文件正在统一作为脚本工作。服务器端文件在主 PC 和桌面应用程序上运行。当我打开服务器和客户端文件时,它们在 pc 上工作。如果我也将这些文件分开到不同的电脑上,它们就可以工作。到这里为止没有任何问题。但是,如果我想构建这个客户端脚本文件 - 它是统一的 - 作为 android apk 并将其移动到我的移动设备,客户端文件正在工作但无法连接到服务器。在电脑上,没有任何错误,但是apk文件有错误。
C# 服务器端代码--
public Form1()
{
InitializeComponent();
}
//public virtual System.Windows.Forms.AnchorStyles Anchor { get; set; }
private void Form1_Load(object sender, EventArgs e)
{
Console.WriteLine(string.Format("Starting TCP and UDP servers on port {0}...", 27015));
devices_battery_midlow_pic_1.Visible = false;
devices_battery_low_pic_1.Visible = false;
devices_battery_midhigh_pic_1.Visible = false;
devices_battery_high_pic_1.Visible = false;
play_button.Anchor = (AnchorStyles.Bottom);
Console.WriteLine(DateTime.Now.ToString() + " Getting IP...");
IPHostEntry ipHostInfo = Dns.GetHostEntry(Dns.GetHostName());
IPAddress ipAddress = ipHostInfo.AddressList[0];
IPAddress ipAddress2 = ipHostInfo.AddressList[1];
connection_id_label.Text = "This IP:\n" + ipAddress2.MapToIPv4().ToString();
Console.WriteLine(DateTime.Now.ToString() + " Starting Connection Thread...");
connectionThread = new Thread(new ThreadStart(StartServer));
connectionThread.IsBackground = true;
connectionThread.Start();
}
private void StartServer()
{
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
TcpListener listener = new TcpListener(IPAddress.Any, 27015);
listener.Start();
while (true)
{
using (TcpClient client = listener.AcceptTcpClient())
{
using (NetworkStream stream = client.GetStream())
{
byte[] buffer = new byte[client.ReceiveBufferSize];
int bytesRead = stream.Read(buffer, 0, client.ReceiveBufferSize);
string dataReceived = Encoding.ASCII.GetString(buffer, 0, bytesRead);
Console.WriteLine($"Received: {dataReceived}");
//Thread staThread = new Thread(() => PasteText(dataReceived));
//staThread.SetApartmentState(ApartmentState.STA);
//staThread.Start();
}
}
}
}
客户端 C# 脚本--
void Start()
{
Debug.Log(string.Format("Starting TCP and UDP clients on port {0}...", 116));
//udpThread = new Thread(new ThreadStart(ClientThread));
//udpThread.Start();
ClientThread();
}
// Update is called once per frame
void Update()
{
}
void OnGUI()
{
if (GUI.Button(new Rect(10, 10, 150, 100), debugString))
{
print("You clicked the button!");
}
}
void ClientThread()
{
using (TcpClient client = new TcpClient("10.10.10.73", 27015))
{
using (NetworkStream stream = client.GetStream())
{
byte[] bytesToSend = ASCIIEncoding.ASCII.GetBytes("asdasd");
stream.Write(bytesToSend, 0, bytesToSend.Length);
}
}
}
这对我来说太重要了。我在等你的帮助。
【问题讨论】:
-
你知道是哪个错误吗?如果可以,请您也发布一下吗?
-
实际上我没有收到任何错误。当我启动 apk 文件时,它启动但未连接到服务器应用程序。
-
从设备日志中检查answers.unity.com/questions/492681/how-to-use-adb-logcat.html 我猜是它的 IP 地址问题,如果你在那里为 tcpclient 使用那个固定值