public void Connect() { _core = _connector.Core.GetNextCore(); if (null == _socket) { _socket = _core.CreateSocket(_connector.AddressFamily , _connector.SocketType, _connector.ProtocolType); } if (!_core.Bind(_socket)) { throw new SocketException(); } int bytesTransferred; if (null != _byteBuffer && 0 < _byteBuffer.Count) { IntPtr bytePointer = Marshal.UnsafeAddrOfPinnedArrayElement( _byteBuffer.Array, _byteBuffer.Begin); if (_socket.ConnectEx(_connector.ConnectTo, bytePointer, _byteBuffer.Count, out bytesTransferred, this.NativeOverlapped, _core)) { return; } } else { if (_socket.ConnectEx(_connector.ConnectTo, IntPtr.Zero, 0, out bytesTransferred, this.NativeOverlapped, _core)) { return; } } if ((int)SocketError.IOPending == Marshal.GetLastWin32Error()) { return; } throw new SocketException(); }
void InitializeConnection(int bytes_transferred, object context) { IntPtr bytePointer = Marshal.UnsafeAddrOfPinnedArrayElement( _byteBuffer.Array, _byteBuffer.End); HazelAddress localAddr = null; HazelAddress remoteAddr = null; HazelSocket.GetAcceptExSockaddrs(bytePointer , 0 , HazelAddress.MaxSize + 4 , HazelAddress.MaxSize + 4 , out localAddr , out remoteAddr); _byteBuffer.End += bytes_transferred; _byteBuffer.Begin += (2 * (HazelAddress.MaxSize + 4)); _socket.SetLocalAddress(localAddr); _socket.SetRemoteAddress(remoteAddr); _socket.SetSockOpt(SocketOptionLevel.Socket, SocketOptionName.UpdateAcceptContext, _socket.Handle); _acceptor.Logger.InfoFormat("获取到来自[{0}]的连接,开始初始化!", _socket.RemoteEndPoint); IOCPCore core = _acceptor.Core.GetNextCore(); if (!core.Bind(_socket)) { Win32Exception err = new Win32Exception(); _acceptor.OnError(new InitializeError(_acceptor.BindPoint, string.Format("初始化来自[{0}]的连接时,绑定到iocp发生错误 - {0}", _socket.RemoteEndPoint, err.Message), err)); return; } InitializeError initializeError = null; ConnectedSocket connectedSocket = null; try { IDictionary <string, object> misc = (null == _acceptor.ProtocolFactory) ? null : _acceptor.ProtocolFactory.Misc; connectedSocket = new ConnectedSocket(core, _socket, new ProtocolContext(null, misc)); IProtocol protocol = _acceptor.CreateProtocol(connectedSocket); core.InitializeConnection(connectedSocket, protocol); _acceptor.Logger.InfoFormat("初始化来自[{0}]的连接成功!", _socket.RemoteEndPoint); _socket = null; } catch (InitializeError e) { initializeError = e; } catch (Exception e) { initializeError = new InitializeError(_socket.RemoteEndPoint, "在处理新连接时发生异常!", e); } if (null != initializeError) { if (null != connectedSocket) { connectedSocket.ReleaseSocket(); } _acceptor.OnError(initializeError); } }