73 lines
1.6 KiB
C#
73 lines
1.6 KiB
C#
using UnityEngine;
|
|
using System.Net.Sockets;
|
|
using System.Net;
|
|
using System.Text;
|
|
using System.Threading;
|
|
|
|
public class DisplayServer : MonoBehaviour
|
|
{
|
|
private TcpListener listener;
|
|
private Thread listenThread;
|
|
private bool isRunning = true;
|
|
|
|
|
|
void Start()
|
|
{
|
|
|
|
listener = new TcpListener(IPAddress.Any, 8888);
|
|
listener.Start();
|
|
|
|
listenThread = new Thread(ListenForClients);
|
|
listenThread.Start();
|
|
|
|
Debug.Log("显示端服务器已启动,等待触摸端连接...");
|
|
}
|
|
|
|
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);
|
|
|
|
|
|
}
|
|
}
|
|
|
|
private void OnApplicationQuit()
|
|
{
|
|
isRunning = false;
|
|
listener.Stop();
|
|
}
|
|
}
|