Esempio n. 1
0
        private void StartRecMsg()
        {
            try
            {
                _udpClient.BeginReceive(asyncCallback =>
                {
                    try
                    {
                        IPEndPoint iPEndPoint = null;
                        byte[] bytes          = _udpClient.EndReceive(asyncCallback, ref iPEndPoint);
                        StartRecMsg();

                        HandleRecMsg?.BeginInvoke(this, iPEndPoint, bytes, null, null);
                    }
                    catch (Exception ex)
                    {
                        HandleException?.BeginInvoke(ex, null, null);
                    }
                }, null);
            }
            catch (Exception ex)
            {
                HandleException?.BeginInvoke(ex, null, null);
            }
        }
Esempio n. 2
0
        private void InitServer()
        {
            _tcpSocketServer.HandleServerStarted = theServer =>
            {
                HandleServerStarted?.Invoke(this);
            };

            _tcpSocketServer.HandleException = ex =>
            {
                HandleException?.Invoke(ex);
            };

            _tcpSocketServer.HandleClientClose = (theServer, theCon) =>
            {
                var webCon = GetConnection(theCon.ConnectionId);
                CloseConnection(webCon);
                HandleClientClose?.Invoke(this, webCon);
            };

            _tcpSocketServer.HandleNewClientConnected = (theServer, theCon) =>
            {
                WebSocketConnection newCon = new WebSocketConnection(this, theCon)
                {
                    HandleClientClose = HandleClientClose == null ? null : new Action <WebSocketServer, WebSocketConnection>(HandleClientClose),
                    HandleSendMsg     = HandleSendMsg == null ? null : new Action <WebSocketServer, WebSocketConnection, string>(HandleSendMsg)
                };

                AddConnection(newCon);

                HandleNewClientConnected?.Invoke(this, newCon);
            };

            _tcpSocketServer.HandleRecMsg = (thServer, theCon, bytes) =>
            {
                string recStr = bytes.ToString(Encoding.UTF8);
                if (IsHandshake(recStr))
                {
                    string res = GetWebSocketResponse(recStr);

                    theCon.Send(res);
                }
                else
                {
                    int opcode = new string(bytes[0].ToBinString().Copy(4, 4).ToArray()).ToInt_FromBinString();

                    //为关闭连接
                    if (opcode == 8)
                    {
                        GetConnection(theCon.ConnectionId).Close();
                    }
                    else
                    {
                        string recData = AnalyticData(bytes);
                        HandleRecMsg?.Invoke(this, GetConnection(theCon.ConnectionId), recData);
                    }
                }
            };
        }
Esempio n. 3
0
        /// <summary>
        /// 开始接受客户端消息
        /// </summary>
        public void StartRecMsg()
        {
            try
            {
                byte[] container = new byte[1024 * 1024 * 4];
                _socket.BeginReceive(container, 0, container.Length, SocketFlags.None, asyncResult =>
                {
                    try
                    {
                        int length = _socket.EndReceive(asyncResult);

                        //马上进行下一轮接受,增加吞吐量
                        if (length > 0 && _isRec && IsSocketConnected())
                        {
                            StartRecMsg();
                        }

                        if (length > 0)
                        {
                            byte[] recBytes = new byte[length];
                            Array.Copy(container, 0, recBytes, 0, length);
                            try
                            {
                                //处理消息
                                HandleRecMsg?.BeginInvoke(recBytes, this, _server, null, null);
                            }
                            catch (Exception ex)
                            {
                                HandleException?.Invoke(ex);
                            }
                        }
                        else
                        {
                            Close();
                        }
                    }
                    catch (Exception ex)
                    {
                        HandleException?.BeginInvoke(ex, null, null);
                        Close();
                    }
                }, null);
            }
            catch (Exception ex)
            {
                HandleException?.BeginInvoke(ex, null, null);
                Close();
            }
        }
Esempio n. 4
0
        private void EndReceiveFrom(IAsyncResult ir)
        {
            if (IsListening)
            {
                UdpState state = ir.AsyncState as UdpState;
                try
                {
                    if (ir.IsCompleted)
                    {
                        int    length     = state.Socket.EndReceiveFrom(ir, ref state.Remote);
                        byte[] btReceived = new byte[length];
                        Buffer.BlockCopy(state.Buffer, 0, btReceived, 0, length);

                        //查询是否UDP连接已经存在
                        SocketConnection connection = GetTheConnection(x =>
                        {
                            var Id = (string)x.Tag;
                            return(Id == state.Remote.ToString());
                        });
                        //如果不存在则新建一个UDP连接对象
                        if (connection == null)
                        {
                            connection = new SocketConnection(state.Remote as IPEndPoint, this)
                            {
                                HandleSendMsg     = HandleSendMsg == null ? null : new Action <byte[], SocketConnection, SocketServer>(HandleSendMsg),
                                HandleClientClose = new Action <SocketConnection, SocketServer>(HandleConnClientClose),
                                HandleException   = HandleException == null ? null : new Action <Exception>(HandleException)
                            };

                            //connection.HandleClientClose += HandleClientClose == null ? null : new Action<SocketConnection, SocketServer>(HandleClientClose);

                            connection.Tag = state.Remote.ToString();
                            AddConnection(connection);
                        }
                        connection.Reactive();
                        HandleRecMsg?.Invoke(btReceived, connection, this);
                    }
                }
                catch (Exception ex)
                {
                    //System.Diagnostics.Trace.WriteLine(DateTime.Now.ToString() + "\t" + ex.Message + ex.Source);
                    HandleException?.Invoke(ex);
                }
                finally
                {
                    state.Socket.BeginReceiveFrom(state.Buffer, 0, state.Buffer.Length, SocketFlags.None, ref state.Remote, new AsyncCallback(EndReceiveFrom), state);
                }
            }
        }
Esempio n. 5
0
        /// <summary>
        /// 开始接受客户端消息
        /// </summary>
        private void StartRecMsg()
        {
            try
            {
                byte[] container = new byte[RecLength];
                _socket.BeginReceive(container, 0, container.Length, SocketFlags.None, asyncResult =>
                {
                    try
                    {
                        int length = _socket.EndReceive(asyncResult);

                        //马上进行下一轮接受,增加吞吐量
                        if (length > 0 && _isRec && IsSocketConnected())
                        {
                            StartRecMsg();
                        }

                        if (length > 0)
                        {
                            byte[] recBytes = new byte[length];
                            Array.Copy(container, 0, recBytes, 0, length);

                            //处理消息
                            HandleRecMsg?.Invoke(this, recBytes);
                        }
                        else
                        {
                            Close();
                        }
                    }
                    //捕捉Socket已释放异常
                    catch (ObjectDisposedException)
                    {
                    }
                    catch (Exception ex)
                    {
                        AccessException(ex);;
                        Close();
                    }
                }, null);
            }
            catch (Exception ex)
            {
                AccessException(ex);;
                Close();
            }
        }
Esempio n. 6
0
        /// <summary>
        /// 读取消息内容
        /// </summary>
        /// <param name="ar"></param>
        public void ReadBodyCallback(IAsyncResult ar)
        {
            try
            {
                String content = String.Empty;
                // Retrieve the state object and the handler socket
                // from the asynchronous state object.
                StateObject state   = (StateObject)ar.AsyncState;
                Socket      handler = state.workSocket;
                // Read data from the client socket.
                int bytesRead = handler.EndReceive(ar);
                if (bytesRead > 0)
                {
                    // There might be more data, so store the data received so far.
                    var bytes = new byte[bytesRead];
                    Array.Copy(state.buffer, 0, state.data, state.dataRecviedLen, bytesRead);

                    state.dataRecviedLen += bytesRead;
                    if (state.dataRecviedLen < state.dataLen)
                    {
                        _socket.BeginReceive(state.buffer, 0, StateObject.BufferSize, SocketFlags.None, new AsyncCallback(ReadBodyCallback), state);
                    }
                    else
                    {
                        try
                        {
                            HandleRecMsg?.BeginInvoke(state.data, this, _server, null, null);
                        }
                        catch (Exception ex)
                        {
                            HandleException?.Invoke(ex);
                        }
                        if (_isRec && IsSocketConnected())
                        {
                            StartRecMsg();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                HandleException?.BeginInvoke(ex, null, null);
                Close();
            }
        }
Esempio n. 7
0
        /// <summary>
        /// 开始接受客户端消息
        /// </summary>
        public void StartRecMsg()
        {
            try
            {
                byte[] container = new byte[_recLength];
                _socket.BeginReceive(container, 0, container.Length, SocketFlags.None, asyncResult =>
                {
                    try
                    {
                        int length = _socket.EndReceive(asyncResult);

                        //马上进行下一轮接受,增加吞吐量
                        if (length > 0 && _isRec && IsSocketConnected() && (!_isClosed))
                        {
                            StartRecMsg();
                        }

                        if (length > 0)
                        {
                            byte[] recBytes = new byte[length];
                            Array.Copy(container, 0, recBytes, 0, length);
                            HandleRecMsg?.Invoke(_server, this, recBytes);
                        }
                        else
                        {
                            Close();
                        }
                    }
                    catch (Exception ex)
                    {
                        AccessException(ex);
                        Close();
                    }
                }, null);
            }
            catch (Exception ex)
            {
                AccessException(ex);
                Close();
            }
        }