Exemple #1
0
        protected static bool _useSecure = false; //

        #endregion Fields

        #region Methods

        //Add a new device to the list of currently connected devices
        private static Device AddDevice(IWebSocketConnection conn, Request requestObject)
        {
            //Create the device
              Device device = new Device()
              {
            AccountName = requestObject.AccountName,
            ConnectionGuid = conn.ConnectionInfo.Id,
            FriendlyName = requestObject.FriendlyName,
            Id = Guid.Empty,
            IP = conn.ConnectionInfo.ClientIpAddress,
            Mode = requestObject.CurrentOperationMode
              };

              //Use the assigned id if the client is supplying one
              if (requestObject.DeviceGuid != null)
            device.Id = new Guid(requestObject.DeviceGuid); //We have a GUID so update to use that for this connection

              //Work out the if we still need a device id and if we do then make one up.
              if (device.Id == Guid.Empty) //If the device does not have a guid then request a new one
              {
            Guid generatedGuid = Guid.NewGuid();
            device.Id = generatedGuid;
              }//if

              //Now actually add the Id to the list
              _connectedDevices.TryAdd(device.Id.ToString(), device);

              //If we wish to send notifications of on / offline devices then send them now
              if (_deviceNotifications)
            NotifyDevices(true,device);

              //Return the device for use in reading
              return device;
        }
        protected int ConfigureIntegrationTestConnectionAndGetId(IWebSocketConnection connection)
        {
            var id = Interlocked.Increment(ref _idSeed);

            connection.OnOpen = () =>
            {
                AddConnection(id, connection);
                Send(id, $"Open: {id}");
            };
            connection.OnClose = () =>
            {
                Send(id, $"Close: {id}");
                RemoveConnection(id);
            };
            connection.OnError = ex =>
            {
                Send(-1, $"Error: {id} - {ex.ToString()}");
            };
            connection.OnMessage = m =>
            {
                Send(id, $"User {id}: {m}");
            };

            return id;
        }
Exemple #3
0
 public WebSocketService NewServiceMap(WebSocketServiceManager _manager, IWebSocketConnection socket)
 {
     WebSocketService service = null;
     switch (_manager.managerName)
     {
         case "/gps":
             service = new GPSService(_manager, socket);
             //service.
             break;
         case "/uhf":
             service = new UHFService(_manager, socket);
             break;
         case "/green_light":
             service = new GreenLightService(_manager, socket);
             break;
         case "/red_light":
             service = new RedLightService(_manager, socket);
             break;
         case "/yellow_light":
             service = new YellowLightService(_manager, socket);
             break;
         case "/fan":
             service = new FanService(_manager, socket);
             break;
         case "/engine":
             service = new EngineService(_manager, socket);
             break;
     }
     return service;
 }
Exemple #4
0
        private void handleGame(IWebSocketConnection socket, String message)
        {
            Room newRoom = JsonConvert.DeserializeObject<Room>(message);
            Room room = Main.ludo.Rooms[newRoom.RoomID];
            room.RoomAction = newRoom.RoomAction;

            if (room.Game.MoveCount == 0)
            {
                room.Game.Fields = ludoLogicHandler.initGame(room);
                Console.WriteLine(" Init Map: " + room.Game.Fields[0, 0]);
            }

            if (room.RoomAction.Equals("rollTheDice"))
            {
                room.Game.DiceValue = rollTheDice();
                room.RoomAction = "diceRolled";
                Console.WriteLine("Rolled Value: " + room.Game.DiceValue);
                room = getUsersTurnID(room);
            }

            Console.WriteLine("It's " + Main.ludo.Users[room.Game.UsersTurnID].UserName + "'s turn!");

            room.Game.MoveCount += 1;
            Main.ludo.Rooms[room.RoomID].Game = room.Game;

            Console.WriteLine("Field: 0 0" + room.Game.Fields[0, 0]);
            Console.WriteLine("Field: 9 0" + room.Game.Fields[9, 0]);

            syncGame();
            //sendGame(room);
        }
Exemple #5
0
 public Player(IWebSocketConnection socket, IPrincipal principal)
 {
     Principal = principal;
     _socket = socket;
     _socket.OnMessage = message => MessageRecieved(this, message);
     _socket.OnClose += LeaveGame;
 }
Exemple #6
0
 /// <summary>
 /// A fleck client, which provides high-level methods to send data to the client (socket).
 /// </summary>
 /// <param name="socket">Client socket connection</param>
 public Client(IWebSocketConnection socket)
 {
     State = ClientState.Unknown;
     Id = null;
     Name = null;
     _socket = socket;
 }
        public void Connection(IWebSocketConnection con, String name)
        {
            if (isNew) isNew = false;

            connections.Add(con, name);
            sendToAllNames();
        }
Exemple #8
0
 private void sendOnlineUsers(IWebSocketConnection socket)
 {
     foreach (var s in onlineUserSocketList.ToList())
     {
         s.Send(JsonConvert.SerializeObject(Main.ludo));
     }
 }
Exemple #9
0
        private void handleRooms(IWebSocketConnection socket, String message)
        {
            Room room = JsonConvert.DeserializeObject<Room>(message);
            Console.WriteLine("JSON: " + message);
            if (room.RoomAction.Equals("createRoom"))
            {
                Console.WriteLine("Room " + room.RoomName + " created");
                createRoom(room);
            }

            if (room.RoomAction.Equals("joinRoom"))
            {
                joinRoom(room);
            }

            if (room.RoomAction.Equals("leaveRoom"))
            {
                leaveRoom(room);
            }

            if (room.RoomAction.Equals("setReady"))
            {
                setReady(room);
            }

            if (room.RoomAction.Equals("setStart"))
            {
                setStart(room);
            }
        }
Exemple #10
0
 public WebSocketService NewServiceMap(WebSocketServiceManager _manager, IWebSocketConnection socket)
 {
     WebSocketService service = null;
     switch (_manager.managerName)
     {
         case "/" + TargetDeiveName.GPS:
             service = new GPSService(_manager, socket);
             break;
         case "/" + TargetDeiveName.UHF:
             service = new UHFService(_manager, socket);
             break;
         case "/" + TargetDeiveName.绿灯:
             service = new GreenLightService(_manager, socket);
             break;
         case "/" + TargetDeiveName.红灯:
             service = new RedLightService(_manager, socket);
             break;
         case "/" + TargetDeiveName.黄灯:
             service = new YellowLightService(_manager, socket);
             break;
         case "/" + TargetDeiveName.电风扇:
             service = new FanService(_manager, socket);
             break;
         case "/" + TargetDeiveName.电机:
             service = new EngineService(_manager, socket);
             break;
     }
     return service;
 }
        public override ChatCommand Execute(IWebSocketConnection socket)
        {
            ChatServer.Instance.ClientConnected(this.ClientName, socket);

            ChatCommandConnected res = new ChatCommandConnected();
            return res;
        }
 public void ServerConfig(IWebSocketConnection socket)
 {
     socket.OnOpen = () => OnOpen(socket);
     socket.OnClose = () => OnClose(socket);
     socket.OnMessage = message => OnMessage(socket, message);
     socket.OnBinary = bytes => OnBinary(socket, bytes);
 }
Exemple #13
0
 //APIClient should be an interface maybe?
 public MersonClient(IWebSocketConnection connection)
     : base()
 {
     this.Connection = connection;
     this.Username = "";
     APIServer.Log.Info("New client created!");
 }
 public void OnOpen(IWebSocketConnection socket)
 {
     Logger.Instance().InfoWithFormat(" >> client {0} - {1} connected.", socket.ConnectionInfo.ClientIpAddress, socket.ConnectionInfo.Id);
     lock (_lockObj)
     {
         _clientSocketList.Add(socket);
     }
 }
Exemple #15
0
 public FanService(WebSocketServiceManager _manager, IWebSocketConnection socket)
 {
     services.register_service("fan", this);
     this.ID = socket.ConnectionInfo.Id.ToString();
     this._manager = _manager;
     this._websocket = socket;
     this._context = socket.ConnectionInfo;
 }
Exemple #16
0
 public void closeConnection(IWebSocketConnection socket)
 {
     foreach (var s in allSockets)
     {
         if (s == socket)
             s.Close();
     }
 }
 public void sendTo(IWebSocketConnection socket) {
     Dem2Hub.sendItTo(this, socket);
     if (operation == 'u' || operation == 'c')
     {
         var subs = new Subscription() { onEntityId = entity.Id };  //we presume, that the entity will be displayed at the client, so we subscribe him
         subs.subscribe(socket);
     }
 }
Exemple #18
0
 public void sendMessage(IWebSocketConnection sock, string msg)
 {
     foreach (var s in allSockets)
     {
         if (s == sock)
             s.Send(msg);
     }
 }
 public void Remove(IWebSocketConnection con)
 {
     if (findIfInList(con))
     {
         connections.Remove(con);
         sendToAllNames();
     }
 }
Exemple #20
0
        private static void Close(IWebSocketConnection socket)
        {
            allSockets.Remove(socket);
            clientWindows.Remove(socket.ConnectionInfo.Id);
            clientDynamicWindows.Remove(socket.ConnectionInfo.Id);

            Console.WriteLine("> Socket to " + socket.ConnectionInfo.ClientIpAddress + " closed");
        }
        public void OnMessage(IWebSocketConnection socket, string message)
        {
            Logger.Instance().InfoWithFormat(" >> received message: {0} from {1} - {2}",
                message,
                socket.ConnectionInfo.ClientIpAddress,
                socket.ConnectionInfo.Id);

            RequestManager.Instance().AddRequest(socket, message);
        }
Exemple #22
0
    // ==========================================
    //  WEBSOCKET
    // ==========================================

    private void SendWebSocket(IWebSocketConnection socket, Bitmap image, ImageFormat format) {

      String base64String = null;
      using (var ms = new MemoryStream()) {
        image.Save(ms, format);
        base64String = Convert.ToBase64String(ms.ToArray());
      }
      SendWebSocket(socket, base64String);
    }
 /// <summary>
 /// Handle Websocket Connection
 /// </summary>
 private void HandleWebsocket(IWebSocketConnection socket)
 {
     socket.OnMessage = message =>
     {
         var update = ReadMessage(message);
         foreach (var observer in _observers.Values)
             observer.OnNext(update);
     };
 }
        public void ClientConnected(string name, IWebSocketConnection socket)
        {
            this.clients.Add(new ChatClient(name, socket));

            SendAll(new ChatCommandClientConnected()
            {
                ClientName = name
            });
        }
        public FleckWebSocketTransport(HostContext context, IJsonSerializer serializer)
        {
            _context = context;
            _serializer = serializer;
            _webSocketConnection = context.GetValue<IWebSocketConnection>("Fleck.IWebSocketConnection");

            // Groups never come from the client
            Groups = Enumerable.Empty<string>();
        }
Exemple #26
0
        public void Close()
        {
            if (Socket != null)
            {
                Socket.OnClose = () => { };
                Socket.Close();
            }

            Socket = null;
        }
        public void OnBinary(IWebSocketConnection socket, byte[] bytes)
        {
            Logger.Instance().InfoWithFormat(">> received {0} bytes from {1} - {2}",
                bytes.Length,
                socket.ConnectionInfo.ClientIpAddress,
                socket.ConnectionInfo.Id);

            var message = Encoding.UTF8.GetString(bytes);
            RequestManager.Instance().AddRequest(socket, message);
        }
Exemple #28
0
 public Socket(IWebSocketConnection socket)
 {
     this._socket = socket;
     this._socket.OnClose = () => this.OnDisconnect(null, null);
     this._socket.OnBinary += (buffer) => this.OnRecv(this, new OnRecvEventArgs(buffer));
     this._socket.OnError += (error) =>
     {
         Log.Error(String.Format("Erro from {0}:{1}: {2}", this._socket.ConnectionInfo.ClientIpAddress, this._socket.ConnectionInfo.ClientPort, error.InnerException));
     };
 }
Exemple #29
0
        public void OnMessage(string _message, IWebSocketConnection _socket)
        {
            string path = _socket.ConnectionInfo.Path;

            WebSocketServiceManager manager = GetWebSocketServiceManager(path, service_list);
            if (manager != null)
            {
                manager.OnMessage(_message, _socket);
            }
        }
        /// <summary>
        ///   Initializes a new instance of the <see cref = "StompWebsocketClient" /> class.
        /// </summary>
        /// <param name = "socket">The socket.</param>
        public StompWebsocketClient(IWebSocketConnection socket)
        {
            if (socket == null) throw new ArgumentNullException("socket");
            _socket = socket;

            socket.OnClose =
                () => { if (OnClose != null) OnClose(); };

            socket.OnMessage = message => OnMessage(_messageSerializer.Deserialize(message));
        }
        public void AddSocketConnection(IWebSocketConnection socket)
        {
            if (!dSocketMsgProc.ContainsKey(socket.ConnectionInfo.Id))
            {
                dSocketMsgProc.Add(socket.ConnectionInfo.Id, socket.ConnectionInfo.PM);
            }
            else if (!allConnectedSockets.Contains(socket))
            {
                throw new Exception("Socket Already connected!");
            }

            if (!allConnectedSockets.Contains(socket))
            {
                allConnectedSockets.Add(socket);
            }
            else
            {
                throw new Exception("Socket Already connected!");
            }
        }
        /// <summary>
        /// Authenticates the specified connection.
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="args">The <see cref="ConnectionOpenedEventArgs"/> instance containing the event data.</param>
        /// <returns></returns>
        private bool Authenticate(IWebSocketConnection sender, ConnectionOpenedEventArgs args)
        {
            string userDomainId = args.Querystrings["userdomainid"];
            string userId       = args.Querystrings["userid"];
            string token        = args.Querystrings["token"];

            //Make sure that we have an ID in the querystring
            if (string.IsNullOrWhiteSpace(userDomainId) || string.IsNullOrEmpty(userId) || string.IsNullOrEmpty(token))
            {
                sender.Close();
                return(false);
            }

            //Assign it to the client identifier
            sender.ClientIdentifier     = $"{userId}";
            sender.Metadata["token"]    = token;
            sender.Metadata["domainId"] = userDomainId;

            return(true);
        }
Exemple #33
0
        /// <summary>
        /// Connect to the WebSocket.
        /// </summary>
        public override async Task Connect()
        {
            await base.Connect();

            _webSocket = WebSocketFactory.Create();

            _webSocket.OnOpened += EmitOpen;
            _webSocket.OnClosed += EmitClose;
            _webSocket.OnError  += error =>
            {
                _link.Logger.Error("WebSocket error: " + error);
            };
            _webSocket.OnMessage += text =>
            {
                EmitMessage(new MessageEvent(text));
            };

            _link.Logger.Info("WebSocket connecting to " + WsUrl);
            _webSocket.Open(WsUrl);
        }
        protected void ProcessDailySettlement(IWebSocketConnection socket, WebSocketSubscribeMessage subscrMsg)
        {
            EvalDailySettlementPriceWarnings(subscrMsg.ServiceKey);


            if (!ProcessDailySettlementThreads.ContainsKey(subscrMsg.ServiceKey))
            {
                lock (tLock)
                {
                    Thread ProcessDailySettlementThread = new Thread(DailySettlementThread);
                    ProcessDailySettlementThread.Start(new object[] { socket, subscrMsg });
                    ProcessDailySettlementThreads.Add(subscrMsg.ServiceKey, ProcessDailySettlementThread);
                }
            }
            else
            {
                DoLog(string.Format("Double subscription for service FD for symbol {0}...", subscrMsg.ServiceKey), MessageType.Information);
                ProcessSubscriptionResponse(socket, "FD", subscrMsg.ServiceKey, subscrMsg.UUID, false, "Double subscription");
            }
        }
        protected void ProcessCreditRecordUpdates(IWebSocketConnection socket, WebSocketSubscribeMessage subscrMsg)
        {
            if (subscrMsg.ServiceKey != "*")
            {
                if (subscrMsg.ServiceKey.EndsWith("@*"))
                {
                    subscrMsg.ServiceKey = subscrMsg.ServiceKey.Replace("@*", "");
                }

                DGTLBackendMock.Common.DTO.Account.CreditRecordUpdate creditRecordUpdate = CreditRecordUpdates.Where(x => x.FirmId == subscrMsg.ServiceKey).FirstOrDefault();

                if (creditRecordUpdate != null)
                {
                    DoSend <DGTLBackendMock.Common.DTO.Account.CreditRecordUpdate>(socket, creditRecordUpdate);
                }
            }


            ProcessSubscriptionResponse(socket, "CU", subscrMsg.ServiceKey, subscrMsg.UUID);
        }
Exemple #36
0
        public Client(IWebSocketConnection socket)
        {
            if (socket == null)
            {
                return;
            }

            var parameter = socket.ConnectionInfo.Path.Replace("/?", "").Split("?");

            Channel    = parameter[0];
            ClientId   = parameter[1];
            ClientName = HttpUtility.UrlDecode(parameter[2], Encoding.UTF8);

            Socket = socket;

            socket.OnMessage = message =>
            {
                MsgSend(message.JsonDeserialize <MsgEntity>());
            };
        }
Exemple #37
0
        /// <summary>
        /// Handles a new incomming web socket connection
        ///
        /// Runs inside some Fleck thread
        /// </summary>
        public void HandleNewConnection(IWebSocketConnection connection)
        {
            var client = new Client(connection, ResolveRoom);

            // client connection
            lock (clients)
                clients.Add(client);

            connection.OnClose = () => {
                client.OnDisconnect();

                // client disconnection
                lock (clients)
                    clients.Remove(client);
            };

            connection.OnOpen = () => client.OnConnect();

            connection.OnMessage = (message) => client.OnMessage(JsonReader.Parse(message).AsJsonObject);
        }
Exemple #38
0
 private static void RefreshClient(IWebSocketConnection socket, ClientSession session,
                                   List <IWebSocketConnection> toClose)
 {
     if (!session.IsLoose)
     {
         if (session.ResetAction())
         {
             MessageSender.RefreshMessage(session, socket);
             MessageSender.BoardMessage(session, socket, grid);
             MessageSender.InfoMessage(session, socket);
             MessageSender.BattleMessage(session, socket);
         }
         else
         {
             MessageSender.BattleMessage(session, socket);
             MessageSender.LooseMessage(session, socket);
             toClose.Add(socket);
         }
     }
 }
Exemple #39
0
 public void Broadcast(string message, IWebSocketConnection skippingSocket = null)
 {
     foreach (var item in sockets)
     {
         var socket = item.Value;
         if (socket != skippingSocket)
         {
             if (socket.IsAvailable)
             {
                 socket.Send(message);
             }
             else
             {
                 IWebSocketConnection removingSocket;
                 sockets.TryRemove(socket.ConnectionInfo.Id, out removingSocket);
                 socket.Close();
             }
         }
     }
 }
        public WebsocketConnect(IWebSocketConnection connection, IO.SerializationContext context, IO.ObjectEncoding encoding)
        {
            this.connection     = connection;
            IsPlaying           = true;
            sendPing            = connection.SendPing;
            connectTime         = DateTime.UtcNow;
            connection.OnPong  += d => callbackManager.SetResult(BitConverter.ToInt32(d, 0), null);
            connection.OnClose += () =>
            {
                OnDisconnected(new ExceptionalEventArgs("Closed"));
            };
            connection.OnError += (e) =>
            {
                OnDisconnected(new ExceptionalEventArgs(e.Message, e));
            };
            var stream = new WebsocketStream(connection);

            writer = new FlvPacketWriter(new IO.AmfWriter(stream, context), encoding);
            reader = new RtmpPacketReader(new IO.AmfReader(stream, context));
        }
        /// <summary>
        /// Called when [text part].
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="args">The <see cref="T:PWebSocketServer.Common.Events.TextMultiFrameEventArgs" /> instance containing the event data.</param>
        public virtual void OnTextPart(IWebSocketConnection sender, TextMultiFrameEventArgs args)
        {
            if (!_partialTextMessages.ContainsKey(sender.UniqueClientIdentifier))
            {
                _partialTextMessages[sender.UniqueClientIdentifier] = args.Message;
            }
            else
            {
                _partialTextMessages[sender.UniqueClientIdentifier] += args.Message;
            }

            if (!args.IsLastFrame)
            {
                return;
            }

            OnText(sender, new TextFrameEventArgs(_partialTextMessages[sender.UniqueClientIdentifier]));

            _partialTextMessages[sender.UniqueClientIdentifier] = null;
        }
Exemple #42
0
 /// <summary>
 /// 服务器链接关闭事件
 /// </summary>
 /// <param name="role">通道标识</param>
 /// <param name="selfId">事件源</param>
 /// <param name="socket">连接信息</param>
 internal void CloseConnection(string role, string selfId, IWebSocketConnection socket)
 {
     if (!RemoveConnection(socket.ConnectionInfo.Id))
     {
         ConsoleLog.Fatal("Sora", "客户端连接被关闭失败");
         ConsoleLog.Warning("Sora", "将在5s后自动退出");
         Thread.Sleep(5000);
         Environment.Exit(-1);
     }
     if (OnCloseConnectionAsync == null)
     {
         return;
     }
     long.TryParse(selfId, out long uid);
     Task.Run(async() =>
     {
         await OnCloseConnectionAsync(socket.ConnectionInfo,
                                      new ConnectionEventArgs(role, uid));
     });
 }
        protected void ProcessUserRecord(IWebSocketConnection socket, WebSocketSubscribeMessage subscrMsg)
        {
            if (subscrMsg.ServiceKey != "*")
            {
                UserRecord userRecord = UserRecords.Where(x => x.UserId == subscrMsg.ServiceKey).FirstOrDefault();

                if (userRecord != null)
                {
                    DoSend <UserRecord>(socket, userRecord);
                }
            }
            else
            {
                foreach (UserRecord userRecord in UserRecords)
                {
                    DoSend <UserRecord>(socket, userRecord);
                }
            }
            ProcessSubscriptionResponse(socket, "TB", subscrMsg.ServiceKey, subscrMsg.UUID);
        }
        public void RemoveSocketConnection(IWebSocketConnection socket)
        {
            if (dSocketMsgProc.ContainsKey(socket.ConnectionInfo.Id))
            {
                dSocketMsgProc.Remove(socket.ConnectionInfo.Id);
            }
            else if (allConnectedSockets.Contains(socket))
            {
                throw new Exception("Socket Already connected!");
            }

            if (allConnectedSockets.Contains(socket))
            {
                allConnectedSockets.Remove(socket);
            }
            else
            {
                throw new Exception("Socket Not Found or Already disconnected!");
            }
        }
Exemple #45
0
 /// <summary>
 /// 服务器链接开启事件
 /// </summary>
 /// <param name="role">通道标识</param>
 /// <param name="selfId">事件源</param>
 /// <param name="socket">连接</param>
 internal void OpenConnection(string role, string selfId, IWebSocketConnection socket)
 {
     //添加服务器记录
     if (!AddConnection(socket.ConnectionInfo.Id, socket, selfId))
     {
         socket.Close();
         ConsoleLog.Error("Sora", $"处理连接请求时发生问题 无法记录该连接[{socket.ConnectionInfo.Id}]");
         return;
     }
     if (OnOpenConnectionAsync == null)
     {
         return;
     }
     long.TryParse(selfId, out long uid);
     Task.Run(async() =>
     {
         await OnOpenConnectionAsync(socket.ConnectionInfo,
                                     new ConnectionEventArgs(role, uid));
     });
 }
Exemple #46
0
        public Player(string playerName, IWebSocketConnection socket, Settings settings)
        {
            Settings = settings;
            Socket   = socket;

            Data      = new PlayerData();
            Data.Name = playerName;
            Data.ID   = Guid.NewGuid().ToString();

            socket.OnClose += () =>
            {
                if (OnConnectionClosed != null)
                {
                    OnConnectionClosed(this, new PlayerConnectionClosed(this, PlayerCloseReason.Disconnected));
                }
            };

            socket.OnMessage += (json) => OnRecieveMessage(json);
            socket.OnBinary  += (bytes) => OnRecieveMessage(Encoding.UTF8.GetString(bytes));
        }
        /// <summary>
        /// Closes a client socket.
        /// </summary>
        /// <param name="connection">The closed <see cref="IWebSocketConnection"/>.</param>
        private void OnCloseConnection(IWebSocketConnection connection)
        {
            if (connection == null)
            {
                throw new ArgumentNullException(paramName: nameof(connection));
            }

            Tuple <string, int> user;

            if (this.clients.TryRemove(key: connection, value: out user))
            {
                this.logger.Format(
                    severity: SeverityLevel.Info,
                    logMessageFormat: "Closes the connection for user {0}.",
                    args: user.Item2);

                this.dataStore.UpdateUserState(userId: user.Item2, state: UserState.Offline);
                this.NotifyUserStateChange(userId: user.Item2, state: UserState.Offline);
            }
        }
Exemple #48
0
        public override void HandleCommand(IWebSocketConnection socket, RemoteConnectionInfo info, Room room)
        {
            if (room != null)
            {
                var result = "Users in this room: ";

                foreach (var user in room.Sockets.OrderBy(socket2 => socket2.GetInfo().Name))
                {
                    result += user.GetInfo().Name + ", ";
                }

                result = result.Remove(result.LastIndexOf(", "));

                info.SendChatMessage(result);
            }
            else
            {
                info.SendChatMessage("You need to join a room to use this command.", Helper.ServerErrorColor);
            }
        }
Exemple #49
0
        public static bool HandlePacket(string intent, IWebSocketConnection socket, Dictionary <string, object> data)
        {
            if (packets.ContainsKey(intent))
            {
                // If any parameter in RequiredParameters doesn't exist in the incoming packet data, return false.
                if (packets[intent].RequiredParams.Any(keyParam => !data.ContainsKey(keyParam)))
                {
                    return(false);
                }

                var info = socket.GetInfo();
                packets[intent].HandlePacket(data, socket, info, info != null                 // room param
                                                                                         ? info.GetRoom()
                                                                                         : null, ref syncHandler.Sockets);
                return(true);
            }

            Console.WriteLine("Unhandled packet: " + intent);
            return(false);
        }
Exemple #50
0
            public SocketHandler(TinyIoCContainer container, IWebSocketConnection conn, WSServer server)
            {
                _logger     = container.Resolve <ILogger>();
                _dispatcher = container.Resolve <EventDispatcher>();
                _conn       = conn;

                conn.OnMessage = OnMessage;
                conn.OnClose   = () =>
                {
                    try
                    {
                        _dispatcher.UnsubscribeAll(this);
                        server._connections.Remove(this);
                    }
                    catch (Exception ex)
                    {
                        _logger.Log(LogLevel.Error, $"Failed to unsubscribe WebSocket connection: {ex}");
                    }
                };
            }
        public void SocketMessage(IWebSocketConnection connection, byte[] data)
        {
            if (_joinedClients.ContainsKey(connection))
            {
                var message = MessageFromClient.Parser.ParseFrom(data);

                switch (message.ClientType)
                {
                case ClientType.ArduinoClient:
                    HandleArduinoMessage(message.ArduinoAction);
                    break;

                case ClientType.WebClient:
                    HandleClientMessage(message.WebClientAction);
                    break;

                default:
                    Console.WriteLine($@"Invalid client type message received {message.ClientType.ToString()}");
                    break;
                }
            }
            else
            {
                var message = MessageFromClient.Parser.ParseFrom(data);

                switch (message.ClientType)
                {
                case ClientType.ArduinoClient:
                    AddArduinoToRoom(message.ArduinoAction.ArduinoJoin, connection);
                    break;

                case ClientType.WebClient:
                    AddWebClientToRoom(message.WebClientAction.WebClientActionJoin, connection);
                    break;

                default:
                    Console.WriteLine($@"Invalid client type message received {message.ClientType.ToString()}");
                    break;
                }
            }
        }
Exemple #52
0
        public static void SecondPhase(IWebSocketConnection socket, Room room, string message) //when client joins a room/ assign teams
        {
            string[] command = message.Split(' ');
            if (command.Length < 2) //wrong command format
            {
                socket.Send("e 0");
                return;
            }
            if (command[0] != "t") //wrong command for 2nd phase
            {
                socket.Send("e 0");
                return;
            }
            if (command[1] != "0" && command[1] != "1") //wrong command format
            {
                socket.Send("e 0");
                return;
            }
            room.preferences[room.sockets.IndexOf(socket)] = command[1] == "1";
            room.playersChose++;

            if (room.playersChose >= 2)
            {
                room.playersChose = 0;
                var sockets = room.sockets;
                if (room.preferences[0] ^ room.preferences[1])
                {
                    sockets[0].Send("t " + (room.preferences[0] ? "1" : "0"));
                    sockets[1].Send("t " + (room.preferences[1] ? "1" : "0"));
                }
                else
                {
                    int t = (new Random()).Next(2);
                    sockets[0].Send("t " + t);
                    sockets[1].Send("t " + (1 - t));
                }
                sockets[0].OnMessage = m => ThirdPhase(sockets[0], room, m);
                sockets[1].OnMessage = m => ThirdPhase(sockets[1], room, m);
            }
            return;
        }
        protected virtual void ProcessClientLoginMock(IWebSocketConnection socket, string m)
        {
            WebSocketLoginMessage wsLogin = JsonConvert.DeserializeObject <WebSocketLoginMessage>(m);


            UserRecord loggedUser = UserRecords.Where(x => x.UserId == wsLogin.UserId).FirstOrDefault();

            DoLog(string.Format("Incoming Login request for user {0}", wsLogin.UUID), MessageType.Information);

            if (loggedUser != null)
            {
                ClientLoginResponse resp = new ClientLoginResponse()
                {
                    Msg          = "ClientLoginResponse",
                    Sender       = wsLogin.Sender,
                    UUID         = wsLogin.UUID,
                    UserId       = wsLogin.UserId,
                    JsonWebToken = _TOKEN
                };


                DoLog(string.Format("user {0} Successfully logged in", wsLogin.UUID), MessageType.Information);
                UserLogged = true;
                DoSend <ClientLoginResponse>(socket, resp);
            }
            else
            {
                ClientReject reject = new ClientReject()
                {
                    Msg          = "ClientReject",
                    Sender       = wsLogin.Sender,
                    UUID         = wsLogin.UUID,
                    UserId       = wsLogin.UserId,
                    RejectReason = string.Format("Invalid user or password")
                };

                DoLog(string.Format("user {0} Rejected because of wrong user or password", wsLogin.UUID), MessageType.Information);
                DoSend <ClientReject>(socket, reject);
                socket.Close();
            }
        }
Exemple #54
0
        public void ClientDidConnect(IWebSocketConnection webSocket)
        {
            var session = _sessionCreationDelegate(webSocket);

            webSocket.OnOpen = () =>
            {
                ++ActiveSessionCount;
                ((App)(Application.Current)).UpdateIconText();
            };
            webSocket.OnMessage = async message => await session.OnMessage(message);

            webSocket.OnBinary = async message => await session.OnBinary(message);

            webSocket.OnClose = () =>
            {
                --ActiveSessionCount;
                ((App)(Application.Current)).UpdateIconText();
                session.Dispose();
                session = null;
            };
        }
Exemple #55
0
        public static void InvestWrok(IWebSocketConnection socket)
        {
            string sql = "select * from InvestCollect";

            var ds     = SqlHelper.GetTableText(sql);
            var dt     = ds[0];
            int length = dt.Rows.Count;

            decimal[] seriesData = new decimal[length];

            for (int j = 0; j < length; j++)
            {
                seriesData[j] = dt.Rows[j].Field <decimal>(1);
            }
            int[] xAxis = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 };


            var reportJson = JsonConvert.SerializeObject(new { xAxis, seriesData });

            socket.Send(reportJson);
        }
        public void ClientDidConnect(IWebSocketConnection webSocket)
        {
            var session = _sessionCreationDelegate(webSocket);

            webSocket.OnOpen = () =>
            {
                ++ActiveSessionCount;
                ActiveSessionCountChanged(this, null);
            };
            webSocket.OnMessage = async message => await session.OnMessage(message);

            webSocket.OnBinary = async message => await session.OnBinary(message);

            webSocket.OnClose = () =>
            {
                --ActiveSessionCount;
                ActiveSessionCountChanged(this, null);
                session.Dispose();
                session = null;
            };
        }
        public void OnBinary(IWebSocketConnection client, byte[] buf)
        {
            log.Write(LogSystem.HOST_SYSTEM, LogType.USER, string.Format("Client {0} send binary: {1}",
                                                                         client.ConnectionInfo.Id,
                                                                         string.Join(" ", buf.Select(x => x.ToString()).ToArray())));

            ////if (buf == null || buf.Length == 0) return;
            ////MSG item = MSG.Deserialize(buf);
            ////if (item == null) return;
            ////MSG_TYPE type = item.Type;
            ////if (type == MSG_TYPE.SET_ID_IN_APP
            ////    || type == MSG_TYPE.SET_ID_IN_COMPUTER
            ////    || type == MSG_TYPE.SET_ID_IN_LAN_INTERNET)
            ////{
            ////    Join(item, client);
            ////}
            ////else
            ////{
            ////    ReceiverData(item);
            ////}
        }
Exemple #58
0
        /// <summary>
        /// 向全员发送信息
        /// </summary>
        /// <param name="wsocketMsg"></param>
        public void SendMessageToAll(WebSocketMessage wsocketMsg)
        {
            string resultData = "";

            if (this.WsResponseTextEventHandler != null)
            {
                WebsocketEventArgs args = new WebsocketEventArgs();
                args.WebSocketMessage = wsocketMsg;
                this.WsResponseTextEventHandler(this, args);
                resultData = args.ResultDataMsg;
            }

            if (!string.IsNullOrWhiteSpace(resultData))
            {
                foreach (DictionaryEntry dey in socketListHs)
                {
                    IWebSocketConnection subConn = (IWebSocketConnection)dey.Value;
                    subConn.Send(resultData);
                }
            }
        }
Exemple #59
0
        private void HandlerMessage(IWebSocketConnection connection, SocketRespons respons)
        {
            if (respons.Error != 0)
            {
                return;
            }
            if (respons.Data == null)
            {
                return;
            }

            switch (respons.Data["Type"].ToObject <int>())
            {
            //todo:根据类型处理不同的消息
            case 1:
            case 2:
            default:
                ReceiveOtherIMEvent?.Invoke(connection, respons.Data.ToObject <ReceiveOtherIMArgs>());
                break;
            }
        }
Exemple #60
0
        public void processMessage(string message, IWebSocketConnection socket)
        {
            OLDMessage receivedMessage = JsonSerializer.Deserialize <OLDMessage>(message);

            if (receivedMessage.type == "GetUser")
            {
                socket.Send(getUserMessage());
            }
            else if (receivedMessage.type == "ChatMessage" || receivedMessage.type == "GetHistory" ||
                     receivedMessage.type == "AddStickyNote" || receivedMessage.type == "User")
            {
                IMessage msg = MessageFactory.createMessageFromString(message, this, socket);

                msg.processInbound();
                msg.processOutbound();
            }
            else
            {
                broadCastMessage(message);
            }
        }