我已经设法设置它,以便我的统一应用程序可以接收 tcp 数据。但是,当我运行该项目时,整个应用程序会冻结,并且在收到消息之前不会做任何事情。然后,一旦收到一条消息,它就会将该消息打印出来,并且不允许我的客户端再次连接到它。
这段代码是我的 TCP 阅读课程的全部内容,我在这里做的一些愚蠢的事情会导致这种情况吗?
有没有更好的方法来读取 TCP 数据?
using UnityEngine;
using System.Collections;
using System.Net.Sockets;
using System.Net;
using System.Text;
using System;
using System.IO;
public class TCPConnection: MonoBehaviour
{
public string ip_address = "";
public int port_number = 0;
void Start()
{
try
{
IPAddress ipAddress = IPAddress.Parse(ip_address);
TcpListener listener = new TcpListener(ipAddress, port_number);
listener.Start();
print("The server is running at port " + port_number);
print("The local end point is :" + listener.LocalEndpoint);
print("Waiting for connection.....");
Socket socket = listener.AcceptSocket();
print("Connection accepted from " + socket.RemoteEndPoint);
byte[] b = new byte[100];
int k = socket.Receive(b);
print("recieved...");
for (int i = 0; i < k; i++)
print (Convert.ToChar(b[i]));
ASCIIEncoding ascii = new ASCIIEncoding();
socket.Send(ascii.GetBytes("The string was recieved by the server"));
print("\nSent ack");
}
catch (Exception e)
{
print("error...." + e.Message);
}
}
}