private void Bind(Socket acceptSocket) { var exSocket = new ExSocket(acceptSocket); exSocket.LastAccessTime = DateTime.Now; var buffer = new byte[this.clientSettings.BufferSize * 2]; this.sendEventArg = new SocketAsyncEventArgs(); this.sendEventArg.SetBuffer(buffer, 0, this.clientSettings.BufferSize); var sendDataToken = new DataToken() { Socket = exSocket }; sendDataToken.bufferOffset = this.sendEventArg.Offset; this.sendEventArg.UserToken = sendDataToken; this.sendEventArg.AcceptSocket = acceptSocket; this.sendEventArg.Completed += new EventHandler <SocketAsyncEventArgs>(IO_Completed); this.receiveEventArg = new SocketAsyncEventArgs(); this.receiveEventArg.SetBuffer(buffer, this.clientSettings.BufferSize, this.clientSettings.BufferSize); var receiveDataToken = new DataToken { Socket = exSocket, SyncSegments = new Queue <ArraySegment <byte> >() }; receiveDataToken.bufferOffset = this.receiveEventArg.Offset; this.receiveEventArg.UserToken = receiveDataToken; this.receiveEventArg.AcceptSocket = acceptSocket; this.receiveEventArg.Completed += new EventHandler <SocketAsyncEventArgs>(IO_Completed); DataReceived += OnReceived; requestHandler.Bind(this); }
private void TryDequeueAndPostSend(ExSocket socket, SocketAsyncEventArgs ioEventArgs) { bool isOwner = ioEventArgs == null; byte[] data; if (socket.TryDequeue(out data)) { if (ioEventArgs == null) { ioEventArgs = ioEventArgsPool.Pop(); ioEventArgs.AcceptSocket = socket.WorkSocket; } DataToken dataToken = (DataToken)ioEventArgs.UserToken; dataToken.Socket = socket; dataToken.byteArrayForMessage = data; dataToken.messageLength = data.Length; try { PostSend(ioEventArgs); } catch { if (isOwner) { ReleaseIOEventArgs(ioEventArgs); } throw; } } else { ReleaseIOEventArgs(ioEventArgs); socket.ResetSendFlag(); } }
public override byte[] BuildMessagePack(ExSocket exSocket, sbyte opCode, byte[] data, int offset, int count) { byte[] buffer = new byte[count + 4]; Buffer.BlockCopy(BitConverter.GetBytes(count), 0, buffer, 0, 4); Buffer.BlockCopy(data, offset, buffer, 4, count); return(buffer); }
private void AddClient(ExSocket socket) { lock (clientSockets) { clientSockets.Add(socket); } }
/// <summary> /// /// </summary> /// <param name="exSocket"></param> /// <param name="opCode"></param> /// <param name="reason"></param> protected void Dispose(ExSocket exSocket, sbyte opCode, string reason) { try { var e = new SocketEventArgs() { Socket = exSocket, Source = new DataMeaage() { OpCode = opCode, Message = reason } }; DoClosed(e); OnDisconnected(e); if (exSocket != null) { exSocket.Close(); } sendEventArg.Dispose(); receiveEventArg.Dispose(); receiveWaitEvent.Dispose(); socketClient.Dispose(); } catch (Exception ex) { TraceLog.WriteError("Dispose connect of client error:{0}", ex); } }
private void TryDequeueAndPostSend(ExSocket socket, SocketAsyncEventArgs ioEventArgs) { SocketAsyncResult result; if (socket.TryDequeue(out result)) { DataToken dataToken = (DataToken)ioEventArgs.UserToken; dataToken.Socket = socket; dataToken.AsyncResult = result; dataToken.byteArrayForMessage = result.Data; dataToken.messageLength = result.Data.Length; try { PostSend(ioEventArgs); } catch (Exception ex) { dataToken.ResultCallback(ResultCode.Error, ex); ResetSendFlag(); } } else { ResetSendFlag(); } }
/// <summary> /// Closes the socket. /// </summary> /// <param name="socket">Socket.</param> public void CloseSocket(ExSocket socket) { try { socket.WorkSocket.Shutdown(SocketShutdown.Both); } catch { } socket.WorkSocket.Close(); }
private void DoClosedStatus(ExSocket socket, int statusCode) { Action <ExSocket, int> handler = OnClosedStatus; if (handler != null) { handler(socket, statusCode); } }
/// <summary> /// /// </summary> /// <param name="socket"></param> /// <param name="opCode"></param> /// <param name="reason"></param> public virtual void SendCloseHandshake(ExSocket socket, sbyte opCode, string reason) { if (MessageProcessor != null) { byte[] data = MessageProcessor.CloseMessage(socket, opCode, reason); if (data != null) { AppServer.SendAsync(socket, data, result => { }); } } }
private void TryDequeueAndPostSend(ExSocket socket, SocketAsyncEventArgs ioEventArgs) { byte[] data; if (socket.TryDequeue(out data)) { DataToken dataToken = (DataToken)ioEventArgs.UserToken; dataToken.Socket = socket; dataToken.byteArrayForMessage = data; dataToken.messageLength = data.Length; PostSend(ioEventArgs); } else { ResetSendFlag(); } }
private void ProcessAccept(SocketAsyncEventArgs acceptEventArgs) { try { Interlocked.Increment(ref _summaryStatus.TotalConnectCount); maxConnectionsEnforcer.WaitOne(); if (acceptEventArgs.SocketError != SocketError.Success) { Interlocked.Increment(ref _summaryStatus.RejectedConnectCount); HandleBadAccept(acceptEventArgs); } else { Interlocked.Increment(ref _summaryStatus.CurrentConnectCount); SocketAsyncEventArgs ioEventArgs = this.ioEventArgsPool.Pop(); ioEventArgs.AcceptSocket = acceptEventArgs.AcceptSocket; var dataToken = (DataToken)ioEventArgs.UserToken; ioEventArgs.SetBuffer(dataToken.bufferOffset, socketSettings.BufferSize); var exSocket = new ExSocket(ioEventArgs.AcceptSocket); exSocket.LastAccessTime = DateTime.Now; dataToken.Socket = exSocket; acceptEventArgs.AcceptSocket = null; //release connect when socket has be closed. ReleaseAccept(acceptEventArgs, false); try { OnConnected(new ConnectionEventArgs { Socket = exSocket }); } catch (Exception ex) { TraceLog.WriteError("OnConnected error:{0}", ex); } PostReceive(ioEventArgs); } } finally { PostAccept(); } }
/// <summary> /// /// </summary> /// <param name="socket"></param> /// <param name="buffer"></param> /// <param name="callback"></param> internal protected override async Task <bool> SendAsync(ExSocket socket, byte[] buffer, Action <SocketAsyncResult> callback) { //socket.Enqueue(buffer, callback); if (socket.DirectSendOrEnqueue(buffer, callback)) { try { TryDequeueAndPostSend(socket, sendEventArg); return(true); } catch (Exception ex) { ResetSendFlag(); TraceLog.WriteError("SendAsync {0} error:{1}", socket.RemoteEndPoint, ex); } } return(false); }
/// <summary> /// /// </summary> /// <param name="socket"></param> /// <param name="buffer"></param> internal protected override bool SendAsync(ExSocket socket, byte[] buffer) { socket.Enqueue(buffer); if (TrySetSendFlag()) { try { TryDequeueAndPostSend(socket, sendEventArg); return(true); } catch { ResetSendFlag(); throw; } } return(false); }
/// <summary> /// /// </summary> /// <param name="socket"></param> /// <param name="buffer"></param> internal protected override bool SendAsync(ExSocket socket, byte[] buffer) { socket.Enqueue(buffer); if (socket.TrySetSendFlag()) { try { TryDequeueAndPostSend(socket, null); return(true); } catch (Exception ex) { socket.ResetSendFlag(); TraceLog.WriteError("SendAsync {0} error:{1}", socket.RemoteEndPoint, ex); } } return(false); }
/// <summary> /// Posts the send. /// </summary> /// <param name="socket">Socket.</param> /// <param name="data">Data.</param> /// <param name="offset">Offset.</param> /// <param name="count">Count.</param> public void PostSend(ExSocket socket, byte[] data, int offset, int count) { byte[] buffer = new byte[count + 4]; Buffer.BlockCopy(BitConverter.GetBytes(count), 0, buffer, 0, 4); Buffer.BlockCopy(data, offset, buffer, 4, count); socket.Enqueue(buffer); if (socket.TrySetSendFlag()) { try { TryDequeueAndPostSend(socket, null); } catch { socket.ResetSendFlag(); throw; } } }
/// <summary> /// /// </summary> /// <param name="exSocket"></param> /// <param name="opCode"></param> /// <param name="reason"></param> protected void Dispose(ExSocket exSocket, sbyte opCode, string reason) { try { var e = new SocketEventArgs() { Socket = exSocket, Source = new DataMeaage() { OpCode = opCode, Message = reason } }; DoClosed(e); OnDisconnected(e); exSocket.Close(); } catch (Exception ex) { logger.Error("OnDisconnected", ex); } }
/// <summary> /// /// </summary> /// <param name="socket"></param> /// <param name="buffer"></param> /// <param name="callback"></param> internal protected override async Task <bool> SendAsync(ExSocket socket, byte[] buffer, Action <SocketAsyncResult> callback) { socket.Enqueue(buffer, callback); return(await Task.Run(() => { if (socket.TrySetSendFlag()) { try { TryDequeueAndPostSend(socket, null); return true; } catch (Exception ex) { socket.ResetSendFlag(); TraceLog.WriteError("SendAsync {0} error:{1}", socket.RemoteEndPoint, ex); } } return false; })); }
private void ProcessAccept(SocketAsyncEventArgs acceptEventArgs) { PostAccept(); if (acceptEventArgs.SocketError != SocketError.Success) { HandleBadAccept(acceptEventArgs); return; } SocketAsyncEventArgs ioEventArgs = this.ioEventArgsPool.Pop(); ioEventArgs.AcceptSocket = acceptEventArgs.AcceptSocket; var dataToken = (DataToken)ioEventArgs.UserToken; ioEventArgs.SetBuffer(dataToken.bufferOffset, socketSettings.BufferSize); var exSocket = new ExSocket(ioEventArgs.AcceptSocket); exSocket.LastAccessTime = DateTime.Now; dataToken.Socket = exSocket; acceptEventArgs.AcceptSocket = null; this.acceptEventArgsPool.Push(acceptEventArgs); //AddClient(exSocket); try { OnConnected(new ConnectionEventArgs { Socket = exSocket }); } catch (Exception ex) { TraceLog.WriteError("OnConnected error:{0}", ex); } PostReceive(ioEventArgs); }
private void TryDequeueAndPostSend(ExSocket socket, SocketAsyncEventArgs ioEventArgs) { bool isOwner = ioEventArgs == null; SocketAsyncResult result; if (socket.TryDequeue(out result)) { if (ioEventArgs == null) { ioEventArgs = ioEventArgsPool.Pop(); ioEventArgs.AcceptSocket = socket.WorkSocket; } DataToken dataToken = (DataToken)ioEventArgs.UserToken; dataToken.Socket = socket; dataToken.AsyncResult = result; dataToken.byteArrayForMessage = result.Data; dataToken.messageLength = result.Data.Length; try { PostSend(ioEventArgs); } catch (Exception ex) { dataToken.ResultCallback(ResultCode.Error, ex); if (isOwner) { ReleaseIOEventArgs(ioEventArgs); } socket.ResetSendFlag(); } } else { ReleaseIOEventArgs(ioEventArgs); socket.ResetSendFlag(); } }
/// <summary> /// /// </summary> /// <param name="socket"></param> /// <param name="data"></param> /// <param name="offset"></param> /// <param name="count"></param> public override async Task PostSend(ExSocket socket, byte[] data, int offset, int count) { await PostSend(socket, OpCode.Binary, data, offset, count); }
/// <summary> /// /// </summary> /// <param name="socket"></param> /// <param name="buffer"></param> /// <param name="callback"></param> public void SendMessage(ExSocket socket, byte[] buffer, Action <SocketAsyncResult> callback) { AppServer.SendAsync(socket, buffer, callback); }
private void TryDequeueAndPostSend(ExSocket socket, SocketAsyncEventArgs ioEventArgs) { bool isOwner = ioEventArgs == null; byte[] data; if (socket.TryDequeue(out data)) { if (ioEventArgs == null) { ioEventArgs = ioEventArgsPool.Pop(); ioEventArgs.AcceptSocket = socket.WorkSocket; } DataToken dataToken = (DataToken)ioEventArgs.UserToken; dataToken.Socket = socket; dataToken.byteArrayForMessage = data; dataToken.messageLength = data.Length; try { PostSend(ioEventArgs); } catch { if (isOwner) ReleaseIOEventArgs(ioEventArgs); throw; } } else { ReleaseIOEventArgs(ioEventArgs); socket.ResetSendFlag(); } }
/// <summary> /// 处理数据接收回调 /// </summary> /// <param name="ioEventArgs"></param> private void ProcessReceive(SocketAsyncEventArgs ioEventArgs) { DataToken dataToken = (DataToken)ioEventArgs.UserToken; if (ioEventArgs.BytesTransferred == 0) { //对方主动关闭socket //if (logger.IsDebugEnabled) logger.Debug("对方关闭Socket"); Closing(ioEventArgs, OpCode.Empty); return; } if (ioEventArgs.SocketError != SocketError.Success) { //Socket错误 logger.Debug("IP {0} ProcessReceive:{1}", (dataToken != null ? dataToken.Socket.RemoteEndPoint.ToNotNullString() : ""), ioEventArgs.SocketError); Closing(ioEventArgs); return; } ExSocket exSocket = dataToken == null ? null : dataToken.Socket; List <DataMeaage> messages; bool hasHandshaked; bool needPostAnother = requestHandler.TryReceiveMessage(ioEventArgs, out messages, out hasHandshaked); if (hasHandshaked) { OnHandshaked(new ConnectionEventArgs { Socket = exSocket }); } //modify reason:数据包接收事件触发乱序 if (messages != null) { foreach (var message in messages) { try { switch (message.OpCode) { case OpCode.Close: var statusCode = requestHandler.MessageProcessor != null ? requestHandler.MessageProcessor.GetCloseStatus(message.Data) : OpCode.Empty; if (statusCode != OpCode.Empty) { DoClosedStatus(exSocket, statusCode); } Closing(ioEventArgs, OpCode.Empty); needPostAnother = false; break; case OpCode.Ping: DoPing(new ConnectionEventArgs { Socket = exSocket, Meaage = message }); break; case OpCode.Pong: DoPong(new ConnectionEventArgs { Socket = exSocket, Meaage = message }); break; default: OnDataReceived(new ConnectionEventArgs { Socket = exSocket, Meaage = message }); break; } } catch (Exception ex) { TraceLog.WriteError("OnDataReceived error:{0}", ex); } } } if (needPostAnother) { PostReceive(ioEventArgs); //是否需要关闭连接 if (exSocket.IsClosed) { ResetSAEAObject(ioEventArgs); } } }
private void TryDequeueAndPostSend(ExSocket socket, SocketAsyncEventArgs ioEventArgs) { bool isOwner = ioEventArgs == null; SocketAsyncResult result; if (socket.TryDequeue(out result)) { if (ioEventArgs == null) { ioEventArgs = ioEventArgsPool.Pop(); ioEventArgs.AcceptSocket = socket.WorkSocket; } DataToken dataToken = (DataToken)ioEventArgs.UserToken; dataToken.Socket = socket; dataToken.AsyncResult = result; dataToken.byteArrayForMessage = result.Data; dataToken.messageLength = result.Data.Length; try { PostSend(ioEventArgs); } catch (Exception ex) { dataToken.ResultCallback(ResultCode.Error, ex); if (isOwner) ReleaseIOEventArgs(ioEventArgs); socket.ResetSendFlag(); } } else { ReleaseIOEventArgs(ioEventArgs); socket.ResetSendFlag(); } }
/// <summary> /// /// </summary> /// <param name="socket"></param> /// <param name="buffer"></param> /// <param name="callback"></param> internal protected override async Task<bool> SendAsync(ExSocket socket, byte[] buffer, Action<SocketAsyncResult> callback) { socket.Enqueue(buffer, callback); return await Task.Run(() => { if (socket.TrySetSendFlag()) { try { TryDequeueAndPostSend(socket, null); return true; } catch (Exception ex) { socket.ResetSendFlag(); TraceLog.WriteError("SendAsync {0} error:{1}", socket.RemoteEndPoint, ex); } } return false; }); }
/// <summary> /// Recover session /// </summary> /// <param name="session"></param> /// <param name="newSessionKey"></param> /// <param name="socket"></param> /// <param name="sendCallback"></param> /// <returns></returns> public static void Recover(GameSession session, Guid newSessionKey, ExSocket socket, Action<ExSocket, byte[], int, int> sendCallback) { var newSession = Get(newSessionKey); if (session != null && newSession != null && session != newSession) { session._exSocket = socket; session._sendCallback = sendCallback; GameSession temp; _globalSession.TryRemove(newSessionKey, out temp); } }
/// <summary> /// /// </summary> /// <param name="socket"></param> public override void Pong(ExSocket socket) { byte[] data = Encoding.UTF8.GetBytes("pong"); PostSend(socket, OpCode.Pong, data, 0, data.Length).Wait(); }
/// <summary> /// /// </summary> /// <param name="socket"></param> /// <param name="reason"></param> public override void CloseHandshake(ExSocket socket, string reason) { requestHandler.SendCloseHandshake(socket, OpCode.Close, reason); }
/// <summary> /// Posts the send. /// </summary> /// <param name="socket">Socket.</param> /// <param name="opCode"></param> /// <param name="data">Data.</param> /// <param name="offset">Offset.</param> /// <param name="count">Count.</param> /// <param name="callback"></param> public override async Task PostSend(ExSocket socket, sbyte opCode, byte[] data, int offset, int count, Action<SocketAsyncResult> callback) { byte[] buffer = requestHandler.MessageProcessor.BuildMessagePack(socket, opCode, data, offset, count); await SendAsync(socket, buffer, callback); }
/// <summary> /// /// </summary> /// <param name="socket"></param> /// <param name="opCode"></param> /// <param name="data"></param> /// <param name="offset"></param> /// <param name="count"></param> public override async Task PostSend(ExSocket socket, sbyte opCode, byte[] data, int offset, int count) { await PostSend(socket, opCode, data, offset, count, result => { }); }
/// <summary> /// /// </summary> /// <param name="socket"></param> /// <param name="reason"></param> public abstract void CloseHandshake(ExSocket socket, string reason);
/// <summary> /// /// </summary> /// <param name="socket"></param> /// <param name="buffer"></param> /// <param name="callback"></param> public void SendMessage(ExSocket socket, byte[] buffer, Action<SocketAsyncResult> callback) { AppServer.SendAsync(socket, buffer, callback); }
private GameSession(Guid sid, ExSocket exSocket, Action<ExSocket, byte[], int, int> sendCallback) : this(sid, null) { InitSocket(exSocket, sendCallback); //添加_remoteAddress 设置,方便打印远程地址 [3/25/2014 lsx] _remoteAddress = exSocket.RemoteEndPoint.ToString(); }
public override byte[] BuildMessagePack(ExSocket exSocket, sbyte opCode, byte[] data, int offset, int count) { byte[] buffer = new byte[count + 4]; Buffer.BlockCopy(BitConverter.GetBytes(count), 0, buffer, 0, 4); Buffer.BlockCopy(data, offset, buffer, 4, count); return buffer; }
private void DoClosedStatus(ExSocket socket, int statusCode) { Action<ExSocket, int> handler = OnClosedStatus; if (handler != null) handler(socket, statusCode); }
protected override void OnClosedStatus(ExSocket socket, int closeStatusCode) { Console.WriteLine("Receive client {0} close status code {1}.", socket.RemoteEndPoint, closeStatusCode); }
/// <summary> /// /// </summary> /// <param name="exSocket"></param> /// <param name="opCode"></param> /// <param name="reason"></param> public override byte[] CloseMessage(ExSocket exSocket, sbyte opCode, string reason) { return null; }
/// <summary> /// /// </summary> /// <param name="socket"></param> /// <param name="reason"></param> public override void CloseHandshake(ExSocket socket, string reason) { Dispose(socket, OpCode.Close, reason); }
private void ProcessAccept(SocketAsyncEventArgs acceptEventArgs) { PostAccept(); if (acceptEventArgs.SocketError != SocketError.Success) { HandleBadAccept(acceptEventArgs); return; } SocketAsyncEventArgs ioEventArgs = this.ioEventArgsPool.Pop(); ioEventArgs.AcceptSocket = acceptEventArgs.AcceptSocket; acceptEventArgs.AcceptSocket = null; this.acceptEventArgsPool.Push(acceptEventArgs); var dataToken = (DataToken)ioEventArgs.UserToken; ioEventArgs.SetBuffer(dataToken.bufferOffset, socketSettings.BufferSize); var exSocket = new ExSocket(ioEventArgs.AcceptSocket); exSocket.LastAccessTime = DateTime.Now; dataToken.Socket = exSocket; AddClient(exSocket); try { OnConnected(new ConnectionEventArgs { Socket = exSocket }); } catch (Exception ex) { TraceLog.WriteError("OnConnected error:{0}", ex); } PostReceive(ioEventArgs); }
/// <summary> /// /// </summary> /// <param name="exSocket"></param> /// <param name="opCode"></param> /// <param name="reason"></param> protected void Dispose(ExSocket exSocket, sbyte opCode, string reason) { try { var e = new SocketEventArgs() { Socket = exSocket, Source = new DataMeaage() { OpCode = opCode, Message = reason } }; DoClosed(e); OnDisconnected(e); if (exSocket != null) exSocket.Close(); } catch (Exception ex) { TraceLog.WriteError("Dispose connect of client error:{0}", ex); } }
/// <summary> /// Posts the send. /// </summary> /// <param name="socket">Socket.</param> /// <param name="opCode"></param> /// <param name="data">Data.</param> /// <param name="offset">Offset.</param> /// <param name="count">Count.</param> /// <param name="callback"></param> public override async Task PostSend(ExSocket socket, sbyte opCode, byte[] data, int offset, int count, Action <SocketAsyncResult> callback) { byte[] buffer = requestHandler.MessageProcessor.BuildMessagePack(socket, opCode, data, offset, count); await SendAsync(socket, buffer, callback); }
/// <summary> /// /// </summary> /// <param name="socket"></param> /// <param name="message"></param> /// <param name="encoding"></param> /// <param name="callback"></param> public void SendMessage(ExSocket socket, string message, Encoding encoding, Action <SocketAsyncResult> callback) { byte[] buffer = encoding.GetBytes(message); SendMessage(socket, buffer, callback); }
private GameSession(Guid sid, ExSocket exSocket, Action<ExSocket, byte[], int, int> sendCallback) : this(sid, null) { InitSocket(exSocket, sendCallback); }
private void socketLintener_OnClosedStatus(ExSocket socket, int closeStatusCode) { try { OnClosedStatus(socket, closeStatusCode); } catch (Exception err) { TraceLog.WriteError("OnPong error:{0}", err); } }
/// <summary> /// /// </summary> /// <param name="socket"></param> /// <param name="closeStatusCode"></param> protected virtual void OnClosedStatus(ExSocket socket, int closeStatusCode) { }
/// <summary> /// /// </summary> /// <param name="exSocket"></param> /// <param name="opCode"></param> /// <param name="reason"></param> public override byte[] CloseMessage(ExSocket exSocket, sbyte opCode, string reason) { return(null); }
/// <summary> /// /// </summary> /// <param name="socket"></param> /// <param name="opCode"></param> /// <param name="reason"></param> public virtual void SendCloseHandshake(ExSocket socket, sbyte opCode, string reason) { if (MessageProcessor != null) { byte[] data = MessageProcessor.CloseMessage(socket, opCode, reason); if (data != null) AppServer.SendAsync(socket, data, result => { }); } }
/// <summary> /// Add session to cache /// </summary> /// <param name="keyCode"></param> /// <param name="socket"></param> /// <param name="sendCallback"></param> public static GameSession CreateNew(Guid keyCode, ExSocket socket, Action<ExSocket, byte[], int, int> sendCallback) { return OnCreate(keyCode, socket, sendCallback); }
/// <summary> /// /// </summary> /// <param name="socket"></param> /// <param name="message"></param> /// <param name="encoding"></param> /// <param name="callback"></param> public void SendMessage(ExSocket socket, string message, Encoding encoding, Action<SocketAsyncResult> callback) { byte[] buffer = encoding.GetBytes(message); SendMessage(socket, buffer, callback); }
private void InitSocket(ExSocket exSocket, Action<ExSocket, byte[], int, int> sendCallback) { _exSocket = exSocket; _sendCallback = sendCallback; }