private void OnSocketAsyncConnectFinish(IAsyncResult result) { Socket socket = (Socket)result.AsyncState; try { socket.EndConnect(result); } catch (ObjectDisposedException) { return; } catch (Exception e) { NetEvent evt = this.netEventPool.GetObject(); evt.type = NetEventType.PeerCantConnect; evt.data = e.Message; NetCommand cmd = this.netCommandPool.GetObject(); cmd.type = NetCommandType.NetEventProxy; cmd.data = evt; this.netCommandQueue.Enqueue(cmd); return; } NetEvent evts = this.netEventPool.GetObject(); evts.type = NetEventType.PeerConnected; this.netEventQueue.Enqueue(evts); SocketReceiveStateObject stateObj = new SocketReceiveStateObject(); stateObj.socket = socket; stateObj.buffer = new byte[10240]; socket.BeginReceive(stateObj.buffer, 0, stateObj.buffer.Length, SocketFlags.None, OnSocketAsyncReceiveFinish, stateObj); }
private void OnSocketAsyncReceiveFinish(IAsyncResult result) { SocketReceiveStateObject stateObj = (SocketReceiveStateObject)result.AsyncState; Socket socket = stateObj.socket; int readBytes = 0; try { readBytes = socket.EndReceive(result); } catch (ObjectDisposedException) { return; } catch (Exception e) { NetEvent evt = this.netEventPool.GetObject(); evt.type = NetEventType.NetWorkError; evt.data = e.Message; NetCommand cmd = this.netCommandPool.GetObject(); cmd.type = NetCommandType.NetEventProxy; cmd.data = evt; this.netCommandQueue.Enqueue(cmd); return; } if (readBytes == 0) { NetEvent evt = this.netEventPool.GetObject(); evt.type = NetEventType.PeerClose; NetCommand cmd = this.netCommandPool.GetObject(); cmd.type = NetCommandType.NetEventProxy; cmd.data = evt; this.netCommandQueue.Enqueue(cmd); } else { NetEvent evt = this.netEventPool.GetObject(); evt.type = NetEventType.RecvMessage; evt.data = new byte[readBytes]; Buffer.BlockCopy(stateObj.buffer, 0, (byte[])evt.data, 0, readBytes); this.netEventQueue.Enqueue(evt); socket.BeginReceive(stateObj.buffer, 0, stateObj.buffer.Length, SocketFlags.None, OnSocketAsyncReceiveFinish, stateObj); } }