Unity 异步网络方案 IOCP Socket + ThreadSafe Queue
Unity IOCP Socket + ThreadSafe Queue 1.Socket.BeginReceive系列接口在unityweb下是不正常的,页面刷新会导致问题 2.自己维护线程,会带来一点小麻烦 3.下面采用iocp+threadsafequeue 来实现异步网络 ``` public class UserToken { public Socket sock; public int offset; public byte[] buf; public bool isBody; public TQueue<byte[]> q; // threadsafe queue public int Len { get { return buf.Length - offset; } } } ``` ``` static void IO_Completed (object sender, SocketAsyncEventArgs e) { switch (e.LastOperation) { case SocketAsyncOperation.Connect: ProcessConnect (e); break; case SocketAsyncOperation.Receive: ProcessReceive (e); break; case SocketAsyncOperation.Send: ProcessSend (e); break; default: Debug.Log ("error: " + e.LastOperation); throw new Exception ("Invalid operation completed"); } } ``` connect后进行receive ``` private static void ProcessConnect (SocketAsyncEventArgs e) { if (e.SocketError == SocketError.Success) { // Successfully connected to the server Debug.Log ("connect success"); var token = e.UserToken as UserToken; var sock = token.sock; var q = token.q; e.UserToken = new UserToken{ sock = sock, q = q, offset = 0, isBody = false, buf = new byte[4] }; var ut = (UserToken)e.UserToken; e.SetBuffer (ut.buf, ut.offset, ut.Len); bool willRaiseEvent = ut.sock.ReceiveAsync (e); if (!willRaiseEvent) { ProcessReceive (e); } } else { throw new SocketException ((int)e.SocketError); } } ``` 使用线程安全的队列接收receive的数据 ``` ut.q.Enqueue (ut.buf); ```