The code is as follows:
usingUnityengine;usingSystem.Collections;usingSystem.Collections.Generic;usingSystem.IO;usingSystem.Net;usingSystem.Net.Sockets;usingSystem.Runtime.InteropServices;namespacesyw_webscoket{ Public classWebsocketmanager:singleton<websocketmanager>{#regionField Public Static stringm_address {Get;Set; }/// <summary>///whether to send/// </summary>Private BOOLIssend;/// <summary>///whether to receive/// </summary>Private BOOLIsrecv;/// <summary>///whether to close/// </summary> Public BOOLIsclose {Get;Set; }//Public string Returnedmessage {get; set;} Public stringMessage {Get;Set; } Public stringRECV {Get;Set; }Privatequeue<string> message_queue =Newqueue<string>();Privatedictionary<string, websocket> m_socketdict =Newdictionary<string, websocket>();#endregion/// <summary>///use the co-process to connect/// </summary>/// <param name= "ws" ></param>/// <returns></returns>IEnumerator Startconnect (stringaddress) {Issend=false; Isrecv=false; Isclose=false; WebSocket ws=Getsocket (address);yield returnws. Connect (); M_address=address; for(inti =0; i < Ws.m_Messages.Count; i++) {Recv=ws. Recvstring ();} while(true){if(issend) {//TODO Send Messagews. Sendstring (Message_queue.dequeue ()); Issend=false; Isrecv=true;}if(ISRECV) {//TODO receives messages for(inti =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 Newwaitforendofframe ();} Ws. Close ();}#regionMethod/// <summary>///Create a WebSocket/// </summary>/// <param name= "Address" >Address</param>/// <returns></returns>PrivateWebSocket Createsocket (stringaddress) {WebSocket ws=NewWebSocket (NewSystem.Uri (address)); M_socketdict.add (address, WS);returnws;}/// <summary>///get a WebSocket/// </summary>/// <param name= "Address" >Address</param>/// <returns></returns> PublicWebSocket Getsocket (stringaddress) {if(M_socketdict.containskey (address))returnm_socketdict[address];returnCreatesocket (address);}/// <summary>///connecting to a server/// </summary>/// <param name= "Address" >Address</param> Public voidConnectsocket (stringaddress) {Startcoroutine (Startconnect (address));}/// <summary>///Send Message/// </summary>/// <param name= "message" ></param> Public voidSend (stringmessage) {message_queue.enqueue (message); Issend=true;}#endregion}}
WebSocket Long Connection