public bool SendMessage(Byte[] data)
        {
            FrameCommandBase command = WebSocketCommandFactory.CreateCommand(data);

            if (!IsConnected())
            {
                Debug.WriteLine("连接已断开,无法发送命令");
                return(false);
            }

            Protocol.WriteCommand(command as INetCommand, this);

            //if (isClosed || (clientSocket != null && !clientSocket.Connected))
            //{
            //    logger.Warn("连接已断开,命令未正确写入");
            //    return false;
            //}

            logger.Trace("SendCommand:{0} {1}\r\n{2}", SessionID, EndPoint, command);
            //lock (objLock)
            //{
            //    SendingMessages++;
            //}
            return(true);
        }
        public bool SendMessage(string content)
        {
            FrameCommandBase command = WebSocketCommandFactory.CreateCommand(content);

            Protocol.WriteCommand(command as INetCommand, this);
            logger.Trace("SendCommand:{0} {1}\r\n{2}", SessionID, EndPoint, command);
            //lock (objLock)
            //{
            //    SendingMessages++;
            //}
            return(true);
        }
        public void Broadcast(Byte[] data, Func <WebSocketSession, bool> check)
        {
            Func <INetSession, bool> innerCheck = (session) =>
            {
                if (session is WebSocketSession)
                {
                    return(check(session as WebSocketSession));
                }
                return(false);
            };
            FrameCommandBase cmd = WebSocketCommandFactory.CreateCommand(data);

            if (cmd != null)
            {
                Broadcast(cmd, innerCheck);
                Logger.Trace("广播消息:\r\n{0}", cmd.ToString());
            }
        }
        public bool SendMessage(Byte[] data, MessageContentType contentType)
        {
            int opcodes = 0;

            if (contentType == MessageContentType.Binary)
            {
                opcodes = Opcodes.BinaryFrame;
            }
            else if (contentType == MessageContentType.Text)
            {
                opcodes = Opcodes.TextFrame;
            }
            else
            {
                logger.Warn("不支持的命令格式:" + contentType.ToString());
                return(false);
            }
            if (!IsConnected())
            {
                Debug.WriteLine("连接已断开,无法发送命令");
                return(false);
            }

            FrameCommandBase command = WebSocketCommandFactory.CreateCommand(data, opcodes);

            //Debug.WriteLine("Client Socket Status(SendMessage):" + SessionID + " " + ClientSocket.Connected.ToString());
            Protocol.WriteCommand(command as INetCommand, this);
            //if (isClosed || (clientSocket != null && !clientSocket.Connected))
            //{
            //    logger.Warn("连接已断开,命令未正确写入");
            //    return false;
            //}

            logger.Trace("SendCommand:{0} {1}\r\n{2}", SessionID, EndPoint, command);
            //lock (objLock)
            //{
            //    SendingMessages++;
            //}
            return(true);
        }
Example #5
0
        protected override void AsyncEventArgs_Completed(object sender, System.Net.Sockets.SocketAsyncEventArgs e)
        {
            //if (e.BytesTransferred <= 0)
            //{
            //    Close();
            //    return;
            //}

            if (e.SocketError != SocketError.Success)
            {
                Debug.WriteLine(String.Format("接收数据时发生异常:{0} {1}", e.SocketError, e.RemoteEndPoint));
                Offline();
                logger.Error("接收数据时发生异常:{0} {1}", e.SocketError, e.RemoteEndPoint);
                return;
            }

            if (e.BytesTransferred == 0)
            {
                Close();
                return;
            }

            ReceivedBytes += e.BytesTransferred - e.Offset;

            for (int i = e.Offset; i < e.Offset + e.BytesTransferred; i++)
            {
                try
                {
                    frameStream.WriteByte(e.Buffer[i]);
                    frameStream.Flush();
                    if (isNoCheck && noCheckCount > 0)
                    {
                        noCheckCount--;
                        continue;
                    }
                    else if (isNoCheck)
                    {
                        isNoCheck    = false;
                        noCheckCount = 0;
                    }

                    if (!IsHandShake && Protocol.IsFrameEnd(frameStream))
                    {
                        frameStream.Position = 0;
                        HandshakeRequestCommand  command     = Protocol.GetCommand(this, frameStream) as HandshakeRequestCommand;
                        HandshakeResponseCommand responseCmd = null;

                        if (command != null)
                        {
                            ProtocolVersion      = command.GetHeader(WebSocketHeader.SecWebSocketAccept) ?? "";
                            this.Url             = command.GetHeader(WebSocketHeader.Url) ?? "";
                            frameStream.Position = 0;
                            frameStream.SetLength(0);
                            responseCmd = command.Execute(this) as HandshakeResponseCommand;
                            if (responseCmd != null && !isClosed)
                            {
                                FrameReader = new FrameStreamReader(frameStream);
                            }
                        }

                        if (responseCmd != null)
                        {
                            Protocol.WriteCommand(responseCmd, this);
                            IsHandShake = true;
                            OnHandshakeCompleted();
                            logger.Debug("客户端握手成功:{0} {1}", SessionID, EndPoint);
                        }
                        else
                        {
                            logger.Warn("客户端握手失败:{0} {1}", SessionID, EndPoint);
                            this.Close();
                        }
                    }
                    else if (IsHandShake)
                    {
                        bool isSuccess = FrameReader.ProcessFrame(this);
                        if (!isSuccess)
                        {
                            HttpCodeResponseCommand cmd = new HttpCodeResponseCommand();
                            cmd.SetHeader(WebSocketHeader.HttpCode, "1002");
                            sendOverClosed = true;
                            Protocol.WriteCommand(cmd, this);
                            logger.Error("接收数据帧发生异常:{0} {1}", SessionID, EndPoint);
                        }
                        else
                        {
                            //
                            if (FrameReader.IsCompleted)
                            {
                                frameStream.Position = 0;
                                frameStream.SetLength(0);
                                logger.Trace("收到数据帧:{0} {1} {2}", SessionID, EndPoint, FrameReader.ToString());
                                FrameCommandBase command = WebSocketCommandFactory.CreateCommand(FrameReader);
                                if (command != null)
                                {
                                    command = command.Execute(this) as FrameCommandBase;
                                    if (command != null)
                                    {
                                        Protocol.WriteCommand(command, this);
                                    }
                                }
                                if (!this.isClosed)
                                {
                                    FrameReader = new FrameStreamReader(frameStream);
                                }
                            }
                            else if (FrameReader.IsContinue)
                            {
                                frameStream.Position = 0;
                                frameStream.SetLength(0);
                                FrameReader.Reset();
                                logger.Trace("收到持续数据帧:{0} {1} {2}", SessionID, EndPoint, FrameReader.ToString());
                            }
                        }
                    }
                }
                catch
                {
                    break;
                }
            }



            if (!isClosed)
            {
                Protocol.TryGetCommand(this);
            }
        }
Example #6
0
        protected override void AsyncEventArgs_Completed(object sender, System.Net.Sockets.SocketAsyncEventArgs e)
        {
            //if (e.BytesTransferred <= 0)
            //{
            //    Offline();
            //    return;
            //}

            if (e.SocketError != SocketError.Success)
            {
                Debug.WriteLine(String.Format("接收数据时发生异常(Client):{0} {1}", e.SocketError, e.RemoteEndPoint));
                Offline();
                logger.Error("接收数据时发生异常:{0} {1}", e.SocketError, e.RemoteEndPoint);
                return;
            }

            if (e.BytesTransferred == 0)
            {
                Close();
                return;
            }

            ReceivedBytes += e.BytesTransferred - e.Offset;

            //logger.Trace("接收:{0} 忽略:{1} FramePayload:{2}", e.BytesTransferred, noCheckCount, FrameReader.FramePayloadLength);
            //if (noCheckCount == 0 && FrameReader.FramePayloadLength == 0)
            //{
            //    StringBuilder sb = new StringBuilder();
            //    for (int i = e.Offset; i < e.Offset + e.BytesTransferred; i++)
            //    {
            //        sb.Append(e.Buffer[i].ToString("x")).Append(" ");
            //    }
            //    logger.Trace("数据:{0}", sb.ToString());
            //}

            for (int i = e.Offset; i < e.Offset + e.BytesTransferred; i++)
            {
                try
                {
                    frameStream.WriteByte(e.Buffer[i]);
                    frameStream.Flush();
                    if (isNoCheck && noCheckCount > 0)
                    {
                        noCheckCount--;
                        continue;
                    }
                    else if (isNoCheck)
                    {
                        isNoCheck    = false;
                        noCheckCount = 0;
                    }

                    if (!IsHandShake && Protocol.IsFrameEnd(frameStream))
                    {
                        frameStream.Position = 0;
                        StreamReader sr      = new StreamReader(frameStream);
                        string       header  = sr.ReadToEnd();
                        Regex        regex   = new Regex("\r\n");
                        string[]     headers = regex.Split(header);

                        if (header != null)
                        {
                            string[] first = header.Split(' ');
                            if (first.Length > 2 && first[1] == "101")
                            {
                                IsHandShake = true;
                                OnHandshakeCompleted();
                            }
                        }


                        frameStream.Position = 0;
                        frameStream.SetLength(0);
                    }
                    else if (IsHandShake)
                    {
                        bool isSuccess = FrameReader.ProcessFrame(this);
                        if (!isSuccess)
                        {
                            //HttpCodeResponseCommand cmd = new HttpCodeResponseCommand();
                            //cmd.SetHeader(WebSocketHeader.HttpCode ,"1002");
                            //sendOverClosed = true;
                            //Protocol.WriteCommand(cmd, this);
                            frameStream.Position = 0;
                            frameStream.SetLength(0);
                            logger.Error("接收数据帧发生异常:{0} {1}", SessionID, EndPoint);
                        }
                        else
                        {
                            //
                            if (FrameReader.IsCompleted)
                            {
                                frameStream.Position = 0;
                                frameStream.SetLength(0);
                                logger.Debug("收到数据帧:{0} {1} {2}", SessionID, EndPoint, FrameReader.ToString());
                                FrameCommandBase command = WebSocketCommandFactory.CreateCommand(FrameReader);
                                if (command != null)
                                {
                                    command = command.Execute(this) as FrameCommandBase;
                                    if (command != null)
                                    {
                                        Protocol.WriteCommand(command, this);
                                    }
                                }
                                if (!this.isClosed)
                                {
                                    FrameReader = new FrameStreamReader(frameStream);
                                }
                            }
                            else if (FrameReader.IsContinue)
                            {
                                frameStream.Position = 0;
                                frameStream.SetLength(0);
                                FrameReader.Reset();
                                logger.Debug("收到持续数据帧:{0} {1} {2}", SessionID, EndPoint, FrameReader.ToString());
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    //此异常发生的可能情况是:处理接收数据的过程中,基础连接被关闭
                    //Debug.WriteLine("Client Socket Status(Received):" + SessionID + " " + ClientSocket.Connected.ToString() + " " + ex.Message);
                    break;
                }
            }



            if (!isClosed)
            {
                Protocol.TryGetCommand(this);
            }
        }