我最近发布了一个有关C#与Java之间的套接字的问题,更具体地说:Unity与Android之间的套接字。这个想法是将Unity与常规的移动应用程序进行通信,以便能够与安装在Unity中模拟环境中的设备(灯,门等)进行交互,我已经成功创建了连接,并且可以打开和关闭灯,并且与设备交互时,问题是:每次我从冻结的Unity手机发送命令时,遵循其执行流程的唯一方法是关闭应用程序,关闭套接字连接,但是,一旦我关闭应用程序, Unity读取接收到的字符串,然后处理该字符串并正确管理组件。我该怎么做才能解决这个问题?我不是C#方面的专家,我一直在寻找信息大约四天,但没有发现太多,流程在line 67: data = stremaReader.ReadLine ();
如果有人能帮助我,我将非常感激,这是一个我必须尽快提出的学术项目,我只需要克服最后的不便就可以实现一切。
Unity与Android之间建立的连接:[1] https://imgur.com/a/fyOhQy4
来自Android客户端的书面数据:[2] https://imgur.com/a/Hnp0F1e
关闭应用程序后接收和处理的数据:[3] https://imgur.com/a/GgOrqpi
这时,可以打开和关闭测试灯,但是必须断开连接。
这是我用Unity / C#编写的服务器类
public class NetworkSocketManager : MonoBehaviour
{
private List<ServerClient> connectedClients;
private List<ServerClient> disconectedClients;
private TcpListener server;
private string data;
public GameObject ligth;
Thread readThread;
private string[] commands;
private NetworkStream stream;
private StreamReader stremaReader;
private bool serverStarted;
public int socketPort = 7691;
private void Start()
{
connectedClients = new List<ServerClient>();
disconectedClients = new List<ServerClient>();
try
{
server = new TcpListener(IPAddress.Parse("192.168.1.64"), socketPort);
server.Start();
serverListening();
serverStarted = true;
Debug.Log("Server started. Port: " + socketPort.ToString());
}
catch (Exception ex)
{
Debug.Log("Server socket error: " + ex);
}
}
private void Update()
{
if (!serverStarted)
return;
foreach (ServerClient client in connectedClients)
{
if (!IsConnected(client.tcp))
{
client.tcp.Close();
disconectedClients.Add(client);
continue;
}
else
{
stream = client.tcp.GetStream();
Debug.Log("Open stream...");
if (stream.DataAvailable)
{
Debug.Log("Received data...");
this.stremaReader = new StreamReader(stream, false);
data = stremaReader.ReadLine();
if (data != null)
OnIcomingData(client, data);
}
}
}
}
private void OnIcomingData(ServerClient client, string data)
{
Debug.Log(client.clientName + " says: " + data);
commands = data.Split(':');
if (commands[0] == "1")
{
ligth.active = true;
}
else if (commands[0] == "0")
{
ligth.active = false;
}
Array.Clear(commands, 0, commands.Length);
data = "";
}
private bool IsConnected(TcpClient tcp)
{
try
{
if (tcp != null && tcp.Client != null && tcp.Client.Connected)
{
if (tcp.Client.Poll(0, SelectMode.SelectRead))
{
return !(tcp.Client.Receive(new byte[1], SocketFlags.Peek) == 0);
}
return true;
}
else
{
return false;
}
}
catch
{
return false;
}
}
private void serverListening()
{
server.BeginAcceptTcpClient(AcceptTcpClient, server);
}
private void AcceptTcpClient(IAsyncResult asyncResult)
{
TcpListener tcplistener = (TcpListener)asyncResult.AsyncState;
connectedClients.Add(new ServerClient(tcplistener.EndAcceptTcpClient(asyncResult)));
serverListening();
}
}
public class ServerClient
{
public TcpClient tcp;
public string clientName;
public ServerClient(TcpClient tcp)
{
this.tcp = tcp;
this.clientName = "Android";
}
}
这是我的Android客户端类:
public class SocketThread extends Thread {
private Socket adviser;
private DataOutputStream dataOut;
@Override
public void run() {
super.run();
Log.e("Status:", "Thread started");
try {
adviser = new Socket("192.168.1.64", 7691);
dataOut = new DataOutputStream(adviser.getOutputStream());
} catch (IOException ex) {
Logger.getLogger(SocketThread.class.getName()).log(Level.SEVERE, null, ex);
}
}
public void sendCommand(String text) {
try {
dataOut.writeUTF(text);
Log.e("Sended Text: ", text);
} catch (IOException ex) {
Logger.getLogger(SocketThread.class.getName()).log(Level.SEVERE, null, ex);
}
}