码迷,mamicode.com
首页 > 编程语言 > 详细

Unity 异步网络方案 IOCP Socket + ThreadSafe Queue

时间:2015-06-03 15:37:00      阅读:296      评论:0      收藏:0      [点我收藏+]

标签:

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);
```

  

Unity 异步网络方案 IOCP Socket + ThreadSafe Queue

标签:

原文地址:http://www.cnblogs.com/lightlfyan/p/4549141.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!