コード例 #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
ファイル: SocketListener.cs プロジェクト: zhangxiangbing/Scut
        private void DoClosedStatus(ExSocket socket, int statusCode)
        {
            Action <ExSocket, int> handler = OnClosedStatus;

            if (handler != null)
            {
                handler(socket, statusCode);
            }
        }
コード例 #9
0
ファイル: RequestHandler.cs プロジェクト: zhangxiangbing/Scut
 /// <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
ファイル: ClientSocket.cs プロジェクト: file1987/Scut
        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
ファイル: ClientSocket.cs プロジェクト: file1987/Scut
 /// <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
ファイル: SocketListener.cs プロジェクト: file1987/Scut
 /// <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
ファイル: SocketListener.cs プロジェクト: zhangxiangbing/Scut
 /// <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
ファイル: SocketListener.cs プロジェクト: zhangxiangbing/Scut
        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
ファイル: SocketListener.cs プロジェクト: zhangxiangbing/Scut
 /// <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
ファイル: RequestHandler.cs プロジェクト: zhangxiangbing/Scut
 /// <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
ファイル: SocketListener.cs プロジェクト: haiya/Scut
 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
ファイル: SocketListener.cs プロジェクト: zhangxiangbing/Scut
        /// <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
ファイル: SocketListener.cs プロジェクト: lvshiling/Scut
 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
ファイル: SocketListener.cs プロジェクト: haiya/Scut
 private void AddClient(ExSocket socket)
 {
     lock (clientSockets)
     {
         clientSockets.Add(socket);
     }
 }
コード例 #26
0
ファイル: SocketListener.cs プロジェクト: lvshiling/Scut
 /// <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
ファイル: GameSession.cs プロジェクト: 87170360/Maximus
 /// <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
ファイル: SocketListener.cs プロジェクト: lvshiling/Scut
 /// <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
ファイル: SocketListener.cs プロジェクト: lvshiling/Scut
 /// <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
ファイル: SocketListener.cs プロジェクト: lvshiling/Scut
 /// <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
ファイル: SocketListener.cs プロジェクト: lvshiling/Scut
 /// <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
ファイル: SocketListener.cs プロジェクト: lvshiling/Scut
 /// <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);
コード例 #34
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);
 }
コード例 #35
0
ファイル: GameSession.cs プロジェクト: 87170360/Maximus
 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
ファイル: SocketListener.cs プロジェクト: haiya/Scut
 /// <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
ファイル: MessageHandler.cs プロジェクト: yunjoker/Scut
 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
ファイル: SocketListener.cs プロジェクト: lvshiling/Scut
 private void DoClosedStatus(ExSocket socket, int statusCode)
 {
     Action<ExSocket, int> handler = OnClosedStatus;
     if (handler != null) handler(socket, statusCode);
 }
コード例 #39
0
ファイル: MainClass.cs プロジェクト: daneric/Scut-samples
 protected override void OnClosedStatus(ExSocket socket, int closeStatusCode)
 {
     Console.WriteLine("Receive client {0} close status code {1}.", socket.RemoteEndPoint, closeStatusCode);
 }
コード例 #40
0
ファイル: MessageHandler.cs プロジェクト: yunjoker/Scut
 /// <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
ファイル: SocketListener.cs プロジェクト: haiya/Scut
 /// <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
ファイル: ClientSocket.cs プロジェクト: huangchenjun/Scut
 /// <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
ファイル: SocketListener.cs プロジェクト: haiya/Scut
        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
ファイル: ClientSocket.cs プロジェクト: huangchenjun/Scut
 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
ファイル: ClientSocket.cs プロジェクト: huangchenjun/Scut
        /// <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
ファイル: SocketListener.cs プロジェクト: zhangxiangbing/Scut
 /// <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
ファイル: SocketListener.cs プロジェクト: zhangxiangbing/Scut
 /// <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
ファイル: SocketListener.cs プロジェクト: zhangxiangbing/Scut
 /// <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
ファイル: RequestHandler.cs プロジェクト: zhangxiangbing/Scut
 /// <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
ファイル: SocketListener.cs プロジェクト: zhangxiangbing/Scut
 /// <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
ファイル: GameSession.cs プロジェクト: JohnnyXq/Scut
 private GameSession(Guid sid, ExSocket exSocket, Action<ExSocket, byte[], int, int> sendCallback)
     : this(sid, null)
 {
     InitSocket(exSocket, sendCallback);
 }
コード例 #53
0
ファイル: GameWebSocketHost.cs プロジェクト: huangbenyu/Scut
 private void socketLintener_OnClosedStatus(ExSocket socket, int closeStatusCode)
 {
     try
     {
         OnClosedStatus(socket, closeStatusCode);
     }
     catch (Exception err)
     {
         TraceLog.WriteError("OnPong error:{0}", err);
     }
 }
コード例 #54
0
ファイル: GameWebSocketHost.cs プロジェクト: huangbenyu/Scut
        /// <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);
 }
コード例 #56
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 => { });
     }
 }
コード例 #57
0
ファイル: GameSession.cs プロジェクト: 87170360/Maximus
 /// <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);
 }
コード例 #58
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);
 }
コード例 #59
0
ファイル: GameSession.cs プロジェクト: 87170360/Maximus
 private void InitSocket(ExSocket exSocket, Action<ExSocket, byte[], int, int> sendCallback)
 {
     _exSocket = exSocket;
     _sendCallback = sendCallback;
 }
コード例 #60
0
ファイル: SocketListener.cs プロジェクト: huangbenyu/Scut
        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();
            }
        }