using System; using System.Diagnostics; using Newtonsoft.Json; using UnityEngine; using WebSocketSharp.Server; public class RaadCodeModel { public int Process { get; set; } public bool IsSucess { get; set; } } /// /// WebSocket 服务器管理器单例类,用于管理 WebSocket 服务器。 /// public class WebSocketServerManager : MonoBehaviour { // 单例实例 private static WebSocketServerManager _instance; // WebSocket 服务端实例 private WebSocketServer _webSocketServer; // WebSocket 服务器地址和端口 private string _url = "ws://127.0.0.1:8878"; public int number=0; // 定义一个委托和事件,用于传递接收到的消息 public delegate void MessageReceivedHandler(ToolsEventModel eventModel); public event MessageReceivedHandler OnMessageReceived; // 获取单例实例 public static WebSocketServerManager Instance { get { if (_instance == null) { // 如果单例实例还不存在,则在场景中创建一个 GameObject 并附加脚本 GameObject obj = new GameObject("WebSocketServerManager"); _instance = obj.AddComponent(); DontDestroyOnLoad(obj); // 保持对象在场景切换时不被销毁 } return _instance; } } // Unity 初始化 private void Awake() { // End(8878); // End(10088); if (_instance != null && _instance != this) { Destroy(gameObject); // 防止重复实例 return; } _instance = this; DontDestroyOnLoad(gameObject); // 保持对象在场景切换时不被销毁 // 初始化 WebSocket 服务器 InitializeWebSocketServer(); } // 初始化 WebSocket 服务器 private void InitializeWebSocketServer() { // 创建 WebSocket 服务器实例 _webSocketServer = new WebSocketServer(_url); // 添加 WebSocket 服务到 "/chat" 路径 _webSocketServer.AddWebSocketService("/tools", () => { var instance = new CustomWebSocketBehavior(); // 订阅 CustomWebSocketBehavior 的消息接收事件 instance.OnMessageReceived += HandleClientMessage; return instance; }); // 启动 WebSocket 服务器 _webSocketServer.Start(); UnityEngine.Debug.Log("WebSocket 服务器已启动,地址: " + _url); } // 停止 WebSocket 服务器 private void OnApplicationQuit() { end_(); } public void end_() { if (_webSocketServer != null) { _webSocketServer.RemoveWebSocketService("/tools"); _webSocketServer.Stop(); _webSocketServer = null; UnityEngine.Debug.Log("WebSocket 服务器已停止。"); UnityEngine.Debug.Log("关闭监听" + _url); } } // 发送消息给所有连接的客户端 public void SendMessage(ToolsEventEnum eventType, object value) { if (_webSocketServer != null && _webSocketServer.IsListening) { foreach (var path in _webSocketServer.WebSocketServices.Paths) { string json = JsonConvert.SerializeObject( new ToolsEventModel() { eventType = eventType.ToString(), data = value }); UnityEngine.Debug.Log(json); var service = _webSocketServer.WebSocketServices[path]; service.Sessions.Broadcast(json); UnityEngine.Debug.Log("已发送消息给所有客户端: " + json); } } } public void SendScore(string value) { if (_webSocketServer != null && _webSocketServer.IsListening) { foreach (var path in _webSocketServer.WebSocketServices.Paths) { string json = "{ \"score\":\"" + value + "\"}"; UnityEngine.Debug.Log(json); var service = _webSocketServer.WebSocketServices[path]; service.Sessions.Broadcast(json); UnityEngine.Debug.Log("已发送消息给所有客户端: " + json); } } } // 处理客户端发送的消息 private void HandleClientMessage(string jsonMessage) { try { // 解析 JSON 数据为 ToolsEventModel 对象 ToolsEventModel eventModel = JsonConvert.DeserializeObject(jsonMessage); UnityEngine.Debug.Log(eventModel); // 触发 OnMessageReceived 事件,将解析后的数据传递给订阅者 OnMessageReceived?.Invoke(eventModel); } catch (Exception ex) { UnityEngine.Debug.LogError("解析 JSON 消息时发生错误: " + ex.Message); } } void ExecuteCommand(string command) { ProcessStartInfo processInfo = new ProcessStartInfo("cmd.exe", "/c " + command) { CreateNoWindow = true, UseShellExecute = false, RedirectStandardOutput = true, RedirectStandardError = true }; using (Process process = Process.Start(processInfo)) { if (process != null) { string output = process.StandardOutput.ReadToEnd(); string error = process.StandardError.ReadToEnd(); process.WaitForExit(); if (!string.IsNullOrEmpty(error)) { UnityEngine.Debug.LogError("Error executing command: " + error); } else { UnityEngine.Debug.Log("Command output: " + output); } } } } void End(int port) { // 需要释放的端口号 int portNumber = port; // 获取占用该端口的进程ID string getPidCommand = $"for /f \"tokens=5\" %a in (\'netstat -ano ^| findstr :{portNumber}\') do taskkill /F /PID %a"; UnityEngine.Debug.Log(getPidCommand+"123456"); // 执行命令 ExecuteCommand(getPidCommand); UnityEngine.Debug.Log("已关闭端口" + port); } }