zoukankan      html  css  js  c++  java
  • 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);
    ```
    

      

  • 相关阅读:
    <整理> 在Bash中添加个人定制的命令
    <整理> linux常用命令及工具
    论文分享:目标检测-YOLO
    Siamese Attentional Keypoint Network for High Performance Visual Tracking--论文笔记
    ubuntu 相关软件设置
    anoconda 神经网络 相关操作
    转载:决策树算法梳理
    转载:XGBOOST算法梳理
    XGB算法梳理
    决策树算法梳理
  • 原文地址:https://www.cnblogs.com/lightlfyan/p/4549141.html
Copyright © 2011-2022 走看看