Пример #1
0
 protected override void OnReceiveBytes(IUserToken userToken, byte[] data)
 {
     ((RCoder)userToken.Unpacker).Unpack(data, (r) =>
     {
         OnMsg.Invoke(userToken, r);
     });
 }
Пример #2
0
 protected override void OnReceived(byte[] data)
 {
     ((RCoder)UserToken.Coder).Unpack(data, (r) =>
     {
         OnMsg?.Invoke(r);
     });
 }
Пример #3
0
        private void _server_OnReceive(object currentObj, byte[] data)
        {
            var userToken = (IUserToken)currentObj;

            ((RUnpacker)(userToken.Unpacker)).Unpack(data, (r) =>
            {
                OnMsg.Invoke(userToken, r);
            });
        }
Пример #4
0
        public static void msg(string str)
        {
            OnMsg tmp = onMsg;

            if (tmp != null)
            {
                tmp(str);
            }
        }
 private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
 {
     this.Focus();
     if (this._mClient != null && this._isConnected)
     {
         try
         {
             var transferStr = "mousemove:" + e.X + "@" + e.Y + "@" + this.Height;
             OnMsg?.Invoke(transferStr.ToString());
             _mClient.SendMessage(Remote, transferStr);
         }
         catch
         {
         }
     }
 }
Пример #6
0
        /// <summary>
        /// Среди зарегистророванных методов находит подходящий по типу сообщения и вызывает его.
        /// </summary>
        public bool CallReader(ReceivedMsg msg)
        {
            Delegate reader;

            if (OnMsg != null)
            {
                OnMsg.Invoke(msg.Msg);
            }

            if (_msgReaders.TryGetValue(msg.Msg.GetType(), out reader))
            {
                reader.DynamicInvoke(msg, msg.Msg);

                return(true);
            }
            else
            {
                return(false);
            }
        }
Пример #7
0
        public void Start()
        {
            Running = true;
            Connect().Wait();

            Task.Run(async() =>
            {
                while (Running)
                {
                    try
                    {
                        await SendMsg(new JObject
                        {
                            ["action"] = "heartbeat",
                            ["data"]   = new JObject
                            {
                                ["client"] = "喵喵喵"
                            }
                        });
                    }
                    catch { }
                    Thread.Sleep(10000);
                }
            });

            Task.Run(async() =>
            {
                byte[] buffer = new byte[1 << 16];
                while (Running)
                {
                    try
                    {
                        using (MemoryStream ms = new MemoryStream())
                        {
                            WebSocketReceiveResult result = null;
                            while (true)
                            {
                                while (result == null)
                                {
                                    try
                                    {
                                        result = client.ReceiveAsync(new ArraySegment <byte>(buffer), CancellationToken.None).Result;
                                    }
                                    catch (AggregateException)
                                    {
                                        Active = false;
                                        if (Running)
                                        {
                                            await Connect();
                                        }
                                    }
                                }

                                if (result.Count == 0)
                                {
                                    result = null;
                                    continue;
                                }

                                ms.Write(buffer, 0, result.Count);
                                if (result.EndOfMessage)
                                {
                                    break;
                                }
                            }

                            OnMsg?.Invoke(JObject.Parse(Encoding.UTF8.GetString(ms.ToArray())));
                        }
                    }
                    catch (Exception e)
                    {
                        this.Log(LoggerLevel.Warn, "Uncaught exception : " + e.ToString());
                    }
                }
            });
        }
        /// <summary>
        /// Tries to connect to a server, and then start a listing loop.
        /// </summary>
        private void Connect()
        {
            if (String.IsNullOrEmpty(Address))
            {
                return;
            }

            IPAddress [] addresses;
            if (Address == "localhost")
            {
                addresses = Dns.GetHostAddresses(Dns.GetHostName());
            }
            else
            {
                addresses = Dns.GetHostAddresses(Address);
            }

            // Loop through the AddressList to obtain the supported AddressFamily. This is to avoid
            // an exception that occurs when the host IP Address is not compatible with the address family
            // (typical in the IPv6 case).
            foreach (IPAddress curAddr in addresses)
            {
                try {
                    IPEndPoint ipe = new IPEndPoint(curAddr, Port);
                    connection = new Socket(ipe.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
                    connection.Connect(ipe);

                    //If we connect, start a simple listining loop.
                    if (connection.Connected)
                    {
                        OnConnection?.Invoke(Address + ":" + Port, ConnectionStatus.Succes);

                        Listner = new Thread(() => {
                            while (true)
                            {
                                byte[] buffer = new byte[MsgSize];
                                int size      = 0;

                                try {
                                    size = connection.Receive(buffer);
                                } catch (SocketException) {
                                    KillConnection = true;
                                    size           = 0;
                                }

                                if (size == 0 && KillConnection)
                                {
                                    OnBadThing?.Invoke();
                                    connection.Close();
                                    connection.Dispose();
                                    break;
                                }
                                //connection.Send(buffer);
                                String temp = Util.BtoS(buffer);

                                OnMsg?.Invoke(connection, temp);

                                Thread.Sleep(100);
                            }
                        });
                        Listner.Start();
                        return;
                    }
                    else
                    {
                        continue;
                    }
                } catch (SocketException) {
                    //something mesed up during our connection attempt.
                    //Wont crash out of the loop since we might have more IPs to try
                    continue;
                }
            }
            OnConnection?.Invoke(Address + ":" + Port, ConnectionStatus.Failure);
            connection = null;
        }
        /// <summary>
        /// As a server, we will listen on the main socket
        /// and spawn of other sockets for incomming connetions.
        ///
        /// Those connections will be maintined untill the die
        /// </summary>
        private void Listen()
        {
            IPAddress [] addresses = Dns.GetHostAddresses(Dns.GetHostName());
            // Create a TCP/IP socket.

            foreach (IPAddress curAddr in addresses)
            {
                try {
                    IPEndPoint ipe = new IPEndPoint(curAddr, Port);
                    connection = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                    connection.Bind(ipe);
                    connection.Blocking = false;
                    connection.Listen(10);

                    IsListining = true;
                    break;
                } catch (SocketException) {
                    //something mesed up during our connection attempt.
                    //Wont crash out of the loop since we might have more IPs to try
                    continue;
                }
            }

            if (!IsListining)
            {
                OnConnection?.Invoke("listen", ConnectionStatus.Failure);
            }
            else
            {
                OnConnection?.Invoke("listen", ConnectionStatus.Succes);

                Listner = new Thread(() => {
                    while (true)
                    {
                        if (!KillConnection)
                        {
                            try {
                                Socket tempListener = connection.Accept();
                                OnConnection?.Invoke(Address + ":" + Port, ConnectionStatus.Succes);

                                new Thread((soc) => {
                                    Socket tempSocket = soc as Socket;
                                    while (true)
                                    {
                                        byte[] buffer = new byte[MsgSize];
                                        if (KillConnection)
                                        {
                                            tempSocket.Shutdown(SocketShutdown.Both);
                                        }
                                        int size = 0;
                                        try {
                                            size = tempSocket.Receive(buffer);

                                            String temp = Util.BtoS(buffer);

                                            OnMsg?.Invoke(tempSocket, temp);
                                        } catch (SocketException e) {
                                            if (e.ErrorCode == (int)SocketError.ConnectionAborted || e.ErrorCode != (int)SocketError.WouldBlock)
                                            {
                                                KillConnection = true;
                                                size           = 0;
                                            }
                                        } catch (ObjectDisposedException) {
                                            break;
                                        }

                                        if (size == 0 && KillConnection)
                                        {
                                            OnBadThing?.Invoke();
                                            tempSocket.Close();
                                            tempSocket.Dispose();
                                            break;
                                        }
                                        Thread.Sleep(100);
                                    }

                                    OnConnection?.Invoke(Address + ":" + Port, ConnectionStatus.Failure);
                                }).Start(tempListener);
                            } catch (SocketException e) {
                                //If the accept call has nothing to accept, this will do nothing
                                //All other errors are re-thrown.
                                if (e.ErrorCode != (int)SocketError.WouldBlock)
                                {
                                    throw e;
                                }
                            }
                        }
                        else
                        {
                            try {
                                connection.Shutdown(SocketShutdown.Both);
                            } catch (SocketException) {
                                //The socket was not connected/listening.
                            }
                            connection.Close();
                            connection.Dispose();
                            break;
                        }
                        Thread.Sleep(100);
                    }
                });
                Listner.Start();
            }
        }
 /// <summary>
 /// 日志消息
 /// </summary>
 /// <param name="ex"></param>
 /// <param name="msg"></param>
 private void onMsg(string msg)
 {
     OnMsg?.Invoke(msg);
 }