示例#1
0
        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);
        }
示例#2
0
        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();
            }
        }
示例#3
0
 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);
 }
示例#4
0
 private void AddClient(ExSocket socket)
 {
     lock (clientSockets)
     {
         clientSockets.Add(socket);
     }
 }
示例#5
0
 /// <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);
     }
 }
示例#6
0
        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();
            }
        }
示例#7
0
 /// <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();
 }
示例#8
0
        private void DoClosedStatus(ExSocket socket, int statusCode)
        {
            Action <ExSocket, int> handler = OnClosedStatus;

            if (handler != null)
            {
                handler(socket, statusCode);
            }
        }
示例#9
0
 /// <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 => { });
         }
     }
 }
示例#10
0
        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();
            }
        }
示例#11
0
        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();
            }
        }
示例#12
0
 /// <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);
 }
示例#13
0
 /// <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);
 }
示例#14
0
 /// <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);
 }
示例#15
0
 /// <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;
         }
     }
 }
示例#16
0
 /// <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);
     }
 }
示例#17
0
 /// <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;
     }));
 }
示例#18
0
        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);
        }
示例#19
0
        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();
            }
        }
示例#20
0
 /// <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);
 }
示例#21
0
 /// <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);
 }
示例#22
0
 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();
     }
 }
示例#23
0
        /// <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);
                }
            }
        }
示例#24
0
 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();
     }
 }
示例#25
0
 private void AddClient(ExSocket socket)
 {
     lock (clientSockets)
     {
         clientSockets.Add(socket);
     }
 }
示例#26
0
 /// <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;
     });
 }
示例#27
0
 /// <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);
     }
 }
示例#28
0
 /// <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();
 }
示例#29
0
 /// <summary>
 /// 
 /// </summary>
 /// <param name="socket"></param>
 /// <param name="reason"></param>
 public override void CloseHandshake(ExSocket socket, string reason)
 {
     requestHandler.SendCloseHandshake(socket, OpCode.Close, reason);
 }
示例#30
0
 /// <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);
 }
示例#31
0
 /// <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 => { });
 }
示例#32
0
 /// <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);
 }
示例#33
0
文件: ISocket.cs 项目: file1987/Scut
 /// <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);
 }
示例#35
0
 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();
 }
示例#36
0
 /// <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();
 }
示例#37
0
 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;
 }
示例#38
0
 private void DoClosedStatus(ExSocket socket, int statusCode)
 {
     Action<ExSocket, int> handler = OnClosedStatus;
     if (handler != null) handler(socket, statusCode);
 }
示例#39
0
 protected override void OnClosedStatus(ExSocket socket, int closeStatusCode)
 {
     Console.WriteLine("Receive client {0} close status code {1}.", socket.RemoteEndPoint, closeStatusCode);
 }
示例#40
0
 /// <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;
 }
示例#41
0
 /// <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;
         }
     }
 }
示例#42
0
 /// <summary>
 /// 
 /// </summary>
 /// <param name="socket"></param>
 /// <param name="reason"></param>
 public override void CloseHandshake(ExSocket socket, string reason)
 {
     Dispose(socket, OpCode.Close, reason);
 }
示例#43
0
        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);
        }
示例#44
0
 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();
     }
 }
示例#45
0
        /// <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);
            }

        }
示例#46
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="socket"></param>
 /// <param name="reason"></param>
 public override void CloseHandshake(ExSocket socket, string reason)
 {
     Dispose(socket, OpCode.Close, reason);
 }
示例#47
0
 /// <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);
 }
示例#48
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="socket"></param>
 /// <param name="reason"></param>
 public override void CloseHandshake(ExSocket socket, string reason)
 {
     requestHandler.SendCloseHandshake(socket, OpCode.Close, reason);
 }
示例#49
0
 /// <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 => { });
 }
示例#50
0
 /// <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);
 }
示例#51
0
 /// <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();
 }
示例#52
0
 private GameSession(Guid sid, ExSocket exSocket, Action<ExSocket, byte[], int, int> sendCallback)
     : this(sid, null)
 {
     InitSocket(exSocket, sendCallback);
 }
示例#53
0
 private void socketLintener_OnClosedStatus(ExSocket socket, int closeStatusCode)
 {
     try
     {
         OnClosedStatus(socket, closeStatusCode);
     }
     catch (Exception err)
     {
         TraceLog.WriteError("OnPong error:{0}", err);
     }
 }
示例#54
0
        /// <summary>
        /// 
        /// </summary>
        /// <param name="socket"></param>
        /// <param name="closeStatusCode"></param>
        protected virtual void OnClosedStatus(ExSocket socket, int closeStatusCode)
        {

        }
示例#55
0
 /// <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 => { });
     }
 }
示例#57
0
 /// <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);
 }
示例#59
0
 private void InitSocket(ExSocket exSocket, Action<ExSocket, byte[], int, int> sendCallback)
 {
     _exSocket = exSocket;
     _sendCallback = sendCallback;
 }
示例#60
0
        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();
            }
        }