using System; using System.IO; using System.Net; using System.Net.Sockets; using System.Text; using System.Threading; using UnityEngine; public class SocketClient { private static SocketClient _instance; public static SocketClient Instance { get { if (_instance == null) { _instance = new SocketClient(); } return _instance; } } private Socket socketWatch = null; public Thread threadWatch = null; private bool isRec = true; public bool isAuthorSuccess = false; private string clientConfigFilePath = Path.Combine(Application.streamingAssetsPath, "serverconfig.json"); public void StartConnect() { AuthorConfig authorConfig = JsonUtility.FromJson(File.ReadAllText(clientConfigFilePath)); socketWatch = new Socket(AddressFamily.InterNetwork , SocketType.Stream , ProtocolType.Tcp); IPAddress address = IPAddress.Parse(authorConfig.UsbConnectIp); IPEndPoint endPoint = new IPEndPoint(address , authorConfig.UsbConnectPort); socketWatch.Connect(endPoint); threadWatch = new Thread(RecMsg); threadWatch.IsBackground = true; threadWatch.Start(); } private void RecMsg() { while (true) { byte[] arrRecMsg = new byte[1024 * 1024]; int length = -1; try { length = socketWatch.Receive(arrRecMsg); if (length == 0) { InfoShow.Instance.LogNetError("已与VLSC断开连接,请重新连接或检查网络状况!"); break; } string str = Encoding.UTF8.GetString(arrRecMsg , 0 , length); if (str.Contains("PNNI_SS_AuthorSucceeded")) { Debug.Log("授权席位获取成功!"); isAuthorSuccess = true; AuthorConfig clientConfig = JsonUtility.FromJson(File.ReadAllText(clientConfigFilePath)); } else if (str.Contains("PNNI_SS_AuthorSeatFull")) { InfoShow.Instance.LogAuthorError("服务授权席位已满,请联系管理员添加授权席位!"); break; } else if (str.Contains("PNNI_SS_IdentifierError")) { InfoShow.Instance.LogError("系统标识符错误,请联系管理员修改标识符!"); break; } else { if (!str.Contains("收到信息")) InfoShow.Instance.LogError(str); } } catch (SocketException ex) { InfoShow.Instance.LogNetError("VLSC连接异常: " + ex.Message); break; } catch (Exception ex) { InfoShow.Instance.LogError("异常:" + ex.Message); break; } Thread.Sleep(100); } } public void SendMsg(string sendMsg) { byte[] strSendMsg = Encoding.UTF8.GetBytes(sendMsg); socketWatch.Send(strSendMsg); Debug.Log("客户端发出:" + DateTime.Now + " " + sendMsg); } /// /// Close the socket safely. /// /// The socket. public void SafeClose() { if (socketWatch == null) { return; } if (!socketWatch.Connected) { return; } try { isRec = false; threadWatch.Abort(); } catch (Exception ex) { Debug.LogError(ex.Message.ToString()); } try { socketWatch.Shutdown(SocketShutdown.Both); socketWatch.Close(); } catch (Exception ex) { Debug.LogError(ex.Message.ToString()); } } }