106 lines
2.3 KiB
C#
106 lines
2.3 KiB
C#
using UnityEngine;
|
||
using System.Net.Sockets;
|
||
using System.Net;
|
||
using System.Text;
|
||
using System.Threading;
|
||
using System.Collections.Generic;
|
||
|
||
public class DisplayServer : MonoBehaviour
|
||
{
|
||
private TcpListener listener;
|
||
private Thread listenThread;
|
||
private bool isRunning = true;
|
||
|
||
public Transform background;
|
||
private string latestMsg = "";
|
||
|
||
|
||
void Start()
|
||
{
|
||
Screen.SetResolution(3328, 1352, false);
|
||
|
||
listener = new TcpListener(IPAddress.Any, 8888);
|
||
listener.Start();
|
||
|
||
listenThread = new Thread(ListenForClients);
|
||
listenThread.Start();
|
||
|
||
Debug.Log("显示端服务器已启动,等待触摸端连接...");
|
||
|
||
ShowPage("首页");
|
||
}
|
||
|
||
private void ListenForClients()
|
||
{
|
||
while (isRunning)
|
||
{
|
||
TcpClient client = listener.AcceptTcpClient();
|
||
Debug.Log("触摸端已连接!");
|
||
|
||
Thread clientThread = new Thread(HandleClientComm);
|
||
clientThread.Start(client);
|
||
}
|
||
}
|
||
|
||
private void HandleClientComm(object clientObj)
|
||
{
|
||
TcpClient tcpClient = (TcpClient)clientObj;
|
||
NetworkStream clientStream = tcpClient.GetStream();
|
||
|
||
byte[] message = new byte[4096];
|
||
int bytesRead;
|
||
|
||
while (isRunning)
|
||
{
|
||
try
|
||
{
|
||
bytesRead = clientStream.Read(message, 0, 4096);
|
||
}
|
||
catch
|
||
{
|
||
Debug.Log("触摸端断开连接");
|
||
break;
|
||
}
|
||
|
||
if (bytesRead == 0) break;
|
||
|
||
string data = Encoding.UTF8.GetString(message, 0, bytesRead);
|
||
Debug.Log("收到指令: " + data);
|
||
latestMsg = data;
|
||
}
|
||
}
|
||
|
||
private void Update()
|
||
{
|
||
if (!string.IsNullOrEmpty(latestMsg))
|
||
{
|
||
if (!string.IsNullOrEmpty(latestMsg))
|
||
{
|
||
ShowPage(latestMsg);
|
||
latestMsg = "";
|
||
}
|
||
}
|
||
}
|
||
|
||
private void ShowPage(string pageName)
|
||
{
|
||
if (background == null)
|
||
{
|
||
Debug.LogError($"BG未绑定!");
|
||
return;
|
||
}
|
||
|
||
foreach (Transform child in background)
|
||
{
|
||
child.gameObject.SetActive(child.name == pageName);
|
||
}
|
||
Debug.Log($"显示端切换页面:{pageName}");
|
||
}
|
||
|
||
private void OnApplicationQuit()
|
||
{
|
||
isRunning = false;
|
||
listener.Stop();
|
||
}
|
||
}
|