代码如下:
using UnityEngine; using System.Collections; using System.Collections.Generic; using System.IO; using System.Net; using System.Net.Sockets; using System.Runtime.InteropServices; namespace SYW_WebScoket { public class WebSocketManager : Singleton<WebSocketManager> { #region Field public static string m_address { get; set; } /// <summary> /// 是否发送 /// </summary> private bool IsSend; /// <summary> /// 是否接收 /// </summary> private bool IsRecv; /// <summary> /// 是否关闭 /// </summary> public bool IsClose { get; set; } //public string ReturnedMessage { get; set; } public string Message { get; set; } public string Recv { get; set; } private Queue<string> message_Queue = new Queue<string>(); private Dictionary<string, WebSocket> m_socketDict = new Dictionary<string, WebSocket>(); #endregion /// <summary> /// 使用协程去连接 /// </summary> /// <param name="ws"></param> /// <returns></returns> IEnumerator StartConnect(string address) { IsSend = false; IsRecv = false; IsClose = false; WebSocket ws = GetSocket(address); yield return ws.Connect(); m_address = address; for (int i = 0; i < ws.m_Messages.Count; i++) { Recv = ws.RecvString(); } while (true) { if (IsSend) { //TODO发送信息 ws.SendString(message_Queue.Dequeue()); IsSend = false; IsRecv = true; } if (IsRecv) { //TODO接收消息 for (int i = 0; i < ws.m_Messages.Count; i++) { Recv = ws.RecvString(); } IsRecv = false; } if (IsClose) { break; } if (ws.error != null) { Debug.LogError("Error: " + ws.error); break; } yield return new WaitForEndOfFrame(); } ws.Close(); } #region Method /// <summary> /// 创建一个 WebSocket /// </summary> /// <param name="address">地址</param> /// <returns></returns> private WebSocket CreateSocket(string address) { WebSocket ws = new WebSocket(new System.Uri(address)); m_socketDict.Add(address, ws); return ws; } /// <summary> /// 得到一个WebSocket /// </summary> /// <param name="address">地址</param> /// <returns></returns> public WebSocket GetSocket(string address) { if (m_socketDict.ContainsKey(address)) return m_socketDict[address]; return CreateSocket(address); } /// <summary> /// 连接服务器 /// </summary> /// <param name="address">地址address</param> public void ConnectSocket(string address) { StartCoroutine(StartConnect(address)); } /// <summary> /// 发送消息 /// </summary> /// <param name="message"></param> public void Send(string message) { message_Queue.Enqueue(message); IsSend = true; } #endregion } }