Exemple #1
0
        public static void Handle(byte[] payloadBytes, ConnectInfo connectionInfo)
        {
            var payloadString = Encoding.UTF8.GetString(payloadBytes);

            if (payloadString.StartsWith("subscribe#"))
            {
                connectionInfo.Topic = payloadString.Split("subscribe#").LastOrDefault();

                ConnectStorage.Add(connectionInfo);
            }
            else
            {
                Load payload = JsonConvert.DeserializeObject <Load>(payloadString);
                Storage.Add(payload);
            }
        }
Exemple #2
0
        private void ReceiveCallBack(IAsyncResult asyncResult)
        {
            ConnectInfo connection = asyncResult.AsyncState as ConnectInfo;

            try
            {
                Socket      senderSocket = connection.Socket;
                SocketError response;
                int         buffSize = senderSocket.EndReceive(asyncResult, out response);

                if (response == SocketError.Success)
                {
                    byte[] payload = new byte[buffSize];
                    Array.Copy(connection.Data, payload, payload.Length);

                    Handler.Handle(payload, connection);
                }
            }catch (Exception e)
            {
                Console.WriteLine($"Can't receive data: {e.Message}");
            }
            finally
            {
                try
                {
                    connection.Socket.BeginReceive(connection.Data, 0, connection.Data.Length, SocketFlags.None, ReceiveCallBack, connection);
                }
                catch (Exception e)
                {
                    Console.WriteLine($"{e.Message}");
                    var address = connection.Socket.RemoteEndPoint.ToString();

                    ConnectStorage.Remove(address);
                    connection.Socket.Close();
                }
            }
        }
Exemple #3
0
        public void MessageWork()
        {
            while (true)
            {
                while (!Storage.IsEmpty())
                {
                    var payload = Storage.GetNext();

                    if (payload != null)
                    {
                        var connections = ConnectStorage.GetConnectionInfosByTopic(payload.Topic);

                        foreach (var connection in connections)
                        {
                            var    payloadString = JsonConvert.SerializeObject(payload);
                            byte[] data          = Encoding.UTF8.GetBytes(payloadString);

                            connection.Socket.Send(data);
                        }
                    }
                }
                Thread.Sleep(TIME);
            }
        }