示例#1
0
        private void OnMessage(string data, IWebSocketConnection socket)
        {
            //Console.WriteLine("Message: " + data);

            Dictionary <string, object> dict;

            try
            {
                dict = JsonConvert.DeserializeObject <Dictionary <string, object> >(data);
            }
            catch (Exception ex)
            {
                var info = socket.GetInfo();

                if (info != null)
                {
                    //socket.GetInfo().SendChatMessage("Invalid data received! (" + ex.Message +")", Helper.ServerExceptionColor);
                    info.SendDisconnect("Invalid data received. (" + ex.Message + ")", Helper.ServerExceptionColor);
                }

                socket.Close();
                return;
            }

            try
            {
                if (!PacketManager.HandlePacket((string)dict["intent"], socket, dict))
                {
                    socket.GetInfo().SendChatMessage("Failed to handle packet: " + (string)dict["intent"]);
                }
            }
            catch (Exception ex)
            {
                var info = socket.GetInfo();
                if (info != null)
                {
                    //info.SendChatMessage("Invalid request! (" + ex.Message + ")", Helper.ServerExceptionColor);
                    info.SendDisconnect("Invalid request. (" + ex + ")", Helper.ServerExceptionColor);
                    Console.WriteLine("(" + Helper.IPString(socket) + ")\n" + ex);

                    Directory.CreateDirectory("Errors");
                    var file = File.CreateText("Errors/" + DateTime.Now.ToString("yyyy_MM_dd-HH-mm-ss--fff") + ".txt");
                    file.WriteLine(Helper.IPString(socket));
                    file.WriteLine("\r\nException: " + ex);
                    file.WriteLine("\r\nStacktrace: " + ex.StackTrace);
                    file.WriteLine("\r\nMethod name: " + ex.TargetSite.Name);
                    file.WriteLine("\r\nConnection info: " + JsonConvert.SerializeObject(socket.ConnectionInfo));
                    file.WriteLine("\r\nData: " + data);
                    file.Close();
                }

                socket.Close();
            }
        }
示例#2
0
        public void handleMessage(byte[] bytes)
        {
            try
            {
                ClientPacket packet = new ClientPacket(bytes);
                Console.WriteLine("SOCKET Packet:" + packet.Id);
                if (packet.Id == 1)
                {
                    int    id        = packet.PopInt();
                    string ssoTicket = packet.PopString();
                    Console.WriteLine(id + "  -  " + ssoTicket);

                    GameClient client = RavenEnvironment.GetGame().GetClientManager().GetClientByUserID(id);

                    if (client == null || client.ssoTicket != ssoTicket)
                    {
                        Console.WriteLine("No coincide.");
                        Console.WriteLine(client.ssoTicket);
                        Console.WriteLine(ssoTicket);
                        socket.Close();
                        return;
                    }

                    client.wsSession = this;
                    this.client      = client;

                    ServerPacket loginSso = new ServerPacket(1);
                    this.send(loginSso);
                }

                if (packet.Id == 2)
                {
                    bool test = packet.PopBoolean();

                    if (client == null)
                    {
                        socket.Close();
                        return;
                    }

                    Console.WriteLine(test);
                }
            }

            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
                throw e;
            }
        }
示例#3
0
        /// <summary>
        /// 获取客户端ID
        /// </summary>
        /// <param name="socket"></param>
        /// <returns></returns>
        private static MessageAuthKey GetAppAuthKey(IWebSocketConnection socket)
        {
            MessageAuthKey      messageAuthKey = null;
            NameValueCollection queryParams    = UriUtil.GetQueryString(socket.ConnectionInfo.Path);
            string appKey = queryParams["appKey"];
            string appId  = queryParams["appId"];
            // string authKeyStr =socket.ConnectionInfo.Path.Substring(socket.ConnectionInfo.Path.LastIndexOf("?") + 1);
            string callbackMsg = "";

            if (string.IsNullOrEmpty(appKey) || string.IsNullOrEmpty(appId))
            {
                callbackMsg = $"appKey或appId 信息不存在,连接被拒绝";
                LOG.Error(callbackMsg);
                socket.Send(callbackMsg);
                socket.Close();
                return(null);
            }
            try
            {
                // 获取agent类型,支持多端同时连接
                EnumUserAgentType enumUserAgentType = NetAssist.GetUserAgentType(socket.ConnectionInfo.Headers["User-Agent"]);
                string            agentType         = EnumUtil.GetEnumName <EnumUserAgentType>((int)enumUserAgentType);

                if (appId_Agent_AuthKeyMap.ContainsKey(appId))
                {
                    if (appId_Agent_AuthKeyMap[appId].ContainsKey(agentType))
                    {
                        return(appId_Agent_AuthKeyMap[appId][agentType]);
                    }
                }
                messageAuthKey = new MessageAuthKey
                {
                    AppId     = appId,
                    AppKey    = appKey,
                    AgentType = agentType
                };

                // @TODO 验证appkey的有限性和appId是否唯一
                return(messageAuthKey);
            }
            catch (Exception ex)
            {
                LOG.Error(ex, ex.Message);
                callbackMsg = $"连接信息缺失,连接被拒绝。详情:{ex.Message}";
                socket.Send(callbackMsg);
                socket.Close();
                return(null);
            }
        }
示例#4
0
 public void Close()
 {
     if (connection != null)
     {
         connection.OnOpened  -= Connection_OnOpened;
         connection.OnMessage -= Connection_OnMessage;
         connection.OnClosed  -= Connection_OnClosed;
         connection.OnError   -= Connection_OnError;
         try {
             connection.Close();
         } catch (Exception e) {
             AVRealtime.PrintLog(string.Format("close websocket error: {0}", e.Message));
         }
     }
 }
示例#5
0
 public virtual void setWebSocket(IWebSocketConnection value)
 {
     if (_webSocket != null)
     {
         try
         {
             _webSocket.Close();
         }
         finally
         {
             //  _socketLock.Release();
         }
     }
     _webSocket = value;
 }
示例#6
0
        private async void Terminal_Closed(object sender, EventArgs e)
        {
            ViewModel.Terminal.Closed         -= Terminal_Closed;
            ViewModel.Terminal.OutputReceived -= Terminal_OutputReceived;
            ViewModel.Terminal.RegisterSelectedTextCallback(null);
            _mediatorTaskCTSource.Cancel();
            await ViewModel.ApplicationView.RunOnDispatcherThread(() =>
            {
                _webView.NavigationCompleted -= _webView_NavigationCompleted;
                _webView.NavigationStarting  -= _webView_NavigationStarting;

                _webView?.Navigate(new Uri("about:blank"));
                Root.Children.Remove(_webView);
                _webView = null;

                _socket.OnOpen    -= OnWebSocketOpened;
                _socket.OnMessage -= OnWebSocketMessage;
                _socket.Close();
                _webSocketServer.Dispose();
                _webSocketServer = null;
                _socket          = null;

                _copyMenuItem.Click  -= Copy_Click;
                _pasteMenuItem.Click -= Paste_Click;


                if (Window.Current.Content is Frame frame && frame.Content is Page mainPage)
                {
                    if (mainPage.Resources["TerminalViewModelToViewConverter"] is TerminalViewModelToViewConverter converter)
                    {
                        converter.RemoveTerminal(ViewModel);
                    }
                }
            });
        }
示例#7
0
        private void Open(IWebSocketConnection socket)
        {
            var v = socket.GetPaarmiter(username);

            //如果未取到用户名,则断开连接
            if (string.IsNullOrWhiteSpace(v))
            {
                socket.Close();
                return;
            }
            if (!userlist.ContainsKey(v))
            {
                userlist.Add(v, socket);
                CreateMsg.Run(updatelist());
            }
            else
            {
                var n = CreateMsg.CreateMsgRequest("在其他地方登入");
                n.RecUserlist.Add(v);
                CreateMsg.Run(n);
                userlist[v].Close();
                userlist.Add(v, socket);
                CreateMsg.Run(updatelist());
            }
        }
示例#8
0
 static void Close(TcpClient client, IWebSocketConnection webSocket, Thread clientThread)
 {
     try
     {
         if (client != null)
         {
             client.Close();
         }
     }
     catch
     {
     }
     try
     {
         if (webSocket != null)
         {
             webSocket.Close();
         }
     }
     catch
     {
     }
     if (clientThread != null)
     {
         try
         {
             clientThread.Abort();
         }
         catch
         {
         }
     }
 }
示例#9
0
        private void OnConnected(IWebSocketConnection context)
        {
            var rtspChannelInfo = rtspChannelFactory.DecodeChannelFromClient(context);

            logger.Info($"New Client for {rtspChannelInfo.Url}");
            var clientSession = new ClientSession(context, rtspChannelInfo.Url);
            IRTSPChannelListener channel;

            if (!rtspChannelList.TryGetValue(rtspChannelInfo.Url, out channel))
            {
                channel = rtspChannelFactory.Create(rtspChannelInfo);
                if (rtspChannelList.TryAdd(channel.RtspChannelUrl, channel))
                {
                    channel.Start();
                }
            }
            try
            {
                if (channel.ClientCount + 1 > clientLimitParChannel)
                {
                    throw new ClientLimitReachedException($"Client limit reached for channel {channel.RtspChannelUrl}");
                }
                channel.AddClient(clientSession);
                clientList.TryAdd(clientSession.Id, clientSession);
                SendStringMessage(context, messageFactory.CreateInitialMessage(channel.Width, channel.Height));
            }
            catch (ClientLimitReachedException ex)
            {
                SendStringMessage(context, messageFactory.CreateMessage(EnumMessage.TooManyClientConnected));
                OnDisconnect(context);
                context.Close();
            }
        }
        protected void ClientHeartbeatThread(object param)
        {
            IWebSocketConnection socket = (IWebSocketConnection)param;

            while (socket.IsAvailable)
            {
                try
                {
                    if (UserLogged)
                    {
                        ClientHeartbeat heartbeatReq = new ClientHeartbeat()
                        {
                            Msg    = "ClientHeartbeatRequest",
                            UserId = "user1",
                            Sender = 0,
                            SeqNum = HeartbeatSeqNum,
                            Time   = 0,
                            UUID   = "user1"
                        };

                        DoSend <ClientHeartbeat>(socket, heartbeatReq);
                        HeartbeatSeqNum++;
                    }

                    Thread.Sleep(2000);
                }
                catch (Exception ex)
                {
                    socket.Close();
                }
            }
        }
示例#11
0
 public async Task CloseAsync()
 {
     await Task.Run(() =>
     {
         _current.Close();
     });
 }
示例#12
0
        private static void OnReceive(IWebSocketConnection socket, string msg)
        {
            Console.WriteLine(msg);

            if (msg == "")
            {
                socket.Close();
            }

            String[] split = msg.Split(',');
            switch (split[0])
            {
            case "video":
                new VideoConvert(split, socket);
                break;

            case "screenshot":
                new ScreenshotConvert(socket);
                break;

            case "image":
                new ImageConvert(socket, split[1]);
                break;
            }
        }
        private void CloseConnection()
        {
            _connectionState = ConnectionState.Disconnected;

            OnDisconnect?.Invoke(_webSocketSession);
            _webSocketSession.Close();
        }
 public void Close()
 {
     if (connection != null)
     {
         connection.Close();
     }
 }
示例#15
0
        private void Close(Exception error)
        {
            try
            {
                if (error != null)
                {
                    Logger.Error($"Client closing due to a error. [{error.ToString()}]");
                }

                if (Room != null && User != null)
                {
                    Room.RoomUserManager.RemoveUser(User.Id);
                }

                CommunicationManager.Remove(this);
            }
            catch (Exception e)
            {
                Logger.Error("Error closing GC => " + e.ToString());
            }

            try
            {
                socket.Close();
            }
            catch
            {
            }
        }
 public void closeSession(IWebSocketConnection socket)
 {
     if (!_sessionRegister.TryRemove(socket.ConnectionInfo.Id, out Session session))
     {
         socket.Close();
     }
 }
示例#17
0
 protected override void Dispose()
 {
     if (IsConnected)
     {
         mWebSocketConnection.Close();
     }
 }
示例#18
0
        internal void MessageRPCClientConnection(IWebSocketConnection webSocket, string message, KeePassRPCService service)
        {
            KeePassRPCClientConnection connection = null;

            lock (_lockRPCClientManagers)
            {
                _lockRPCClientManagers.HeldBy = Thread.CurrentThread.ManagedThreadId;
                foreach (KeePassRPCClientManager manager in _RPCClientManagers.Values)
                {
                    foreach (KeePassRPCClientConnection conn in manager.CurrentRPCClientConnections)
                    {
                        if (conn.WebSocketConnection == webSocket)
                        {
                            connection = conn;
                            break;
                        }
                    }
                    if (connection != null)
                    {
                        break;
                    }
                }
            }

            if (connection != null)
            {
                connection.ReceiveMessage(message, service);
            }
            else
            {
                webSocket.Close();
            }
        }
        internal Task Close()
        {
            var tcs = new TaskCompletionSource <bool>();

            void onClose()
            {
                ws.OnClosed -= onClose;
                tcs.SetResult(true);
            }

            ws.OnMessage -= OnWebSocketMessage;
            ws.OnClosed  -= OnWebSocketDisconnected;
            ws.OnError   -= OnWebSocketError;
            ws.OnClosed  += onClose;
            ws.Close();
            return(tcs.Task);
        }
        public void registerSession(IWebSocketConnection socket)
        {
            Session session = new Session(socket);

            if (!_sessionRegister.TryAdd(socket.ConnectionInfo.Id, session))
            {
                socket.Close();
            }
        }
示例#21
0
 protected virtual void Dispose(bool disposing)
 {
     if (disposing)
     {
         if (_webSocket != null)
         {
             _webSocket.Close();
         }
     }
 }
示例#22
0
 protected override Task <Task> StartCoreAsync()
 {
     try
     {
         if (CancellationToken.IsCancellationRequested)
         {
             _webSocket.Close();
             return(Task.FromResult(TaskConstants.Completed));
         }
         _writer.Start();
         _log.Trace("Connected");
         return(Task.FromResult(ProcessAsync()));
     }
     catch
     {
         _webSocket.Close();
         throw;
     }
 }
示例#23
0
        /// <summary>
        /// Disconnect from the WebSocket.
        /// </summary>
        public override void Disconnect()
        {
            base.Disconnect();

            if (_webSocket != null)
            {
                _webSocket.Close();
                _webSocket.Dispose();
            }
        }
 public void Close()
 {
     if (connection != null)
     {
         connection.Close();
         connection.OnOpened  -= Connection_OnOpened;
         connection.OnMessage -= Connection_OnMessage;
         connection.OnClosed  -= Connection_OnClosed;
     }
 }
示例#25
0
        private static void DoWork(IWebSocketConnection socket, IMemeRepository memeRepo)
        {
            var  id       = socket.ConnectionInfo.Path.Substring(1);
            Meme resource = null;

            try { resource = memeRepo.Get(new Guid(id)); }
            catch (Exception e) {}
            if (resource == null)
            {
                socket.Send("NOTFOUND");
                socket.Close();
                return;
            }
            bool       completed = false;
            int        num       = -1;
            WorkStatus status    = resource.MemeWork.Status;

            while (!completed)
            {
                if (resource.MemeWork.Percentage == num)
                {
                    continue;
                }
                if (resource.MemeWork.Status == WorkStatus.Done)
                {
                    completed = true;
                }
                num = resource.MemeWork.Percentage;
                String response = $"{num:D2}\n";
                socket.Send(response);
                if (resource.MemeWork.Percentage == 100)
                {
                    while (Utils.IsFileLocked(new FileInfo(resource.FilePath)))
                    {
                        Thread.Sleep(200);
                    }
                    socket.Send("DONE\n");
                }
            }
            socket.Close();
            memeRepo.Next();
        }
示例#26
0
        public void Close()
        {
            LoginRequired();

            _webSocketConnection.Send("close", false);

            _isLoggedIn   = false;
            _isSubscribed = false;

            _webSocketConnection.Close();
        }
示例#27
0
 private void OnConnected(IWebSocketConnection context)
 {
     if (UserList.Count < ClientLimit)
     {
         UserList[context.ConnectionInfo.Id] = context;
     }
     else
     {
         context.Close();
     }
 }
示例#28
0
        /// <summary>
        /// Completely shuts down a targeted Socket
        /// </summary>
        /// <param name="Socket"></param>
        public void DeactivateSocket(IWebSocketConnection Socket)
        {
            if (this._webSockets.ContainsKey(Socket))
            {
                WebSocketUser user = null;
                this._webSockets[Socket].Closing = true;
                this._webSockets[Socket].Dispose();
                this._webSockets.TryRemove(Socket, out user);
            }

            Socket.Close();
        }
        protected override async Task <Task> StartCoreAsync()
        {
            try
            {
                if (CancellationToken.IsCancellationRequested)
                {
                    _webSocket.Close();
                    return(Task.FromResult(TaskConstants.Completed));
                }
                await _connectCompletion.Task.WithCancellation(CancellationToken).ConfigureAwait(false);

                _writer.Start();
                _log.Trace("Connected");
                return(ProcessAsync());
            }
            catch
            {
                _webSocket.Close();
                throw;
            }
        }
示例#30
0
        internal void Stop()
        {
            if (User != null)
            {
                User.OnDisconnect();
            }

            if (Connection != null)
            {
                Connection.Close();
                Connection = null;
            }
        }
示例#31
0
        private void OnOpenConnection(IWebSocketConnection socket)
        {
            var authCookie = socket.ConnectionInfo.Cookies[FormsAuthentication.FormsCookieName];

            Player player;

            if (authCookie == null || !TryCreatePlayer(authCookie, socket, out player))
            {
                socket.Close();
                return;
            }

            Guid gameGuid;

            if (Guid.TryParse(socket.ConnectionInfo.Path.Replace("", String.Empty), out gameGuid))
            {
                if (_games.Any(g => g.Id == gameGuid))
                {
                    _games.Single(g => g.Id == gameGuid).AddPlayer(player);
                }
            }
        }
示例#32
0
        private void OnConfig(IWebSocketConnection socket)
        {
            var connection = new Connection(socket, _packetSerializer);

            socket.OnOpen += () => Connected(connection);
            socket.OnClose += () => Disconnected(connection);
            //socket.OnBinary += (data) => DataRecieved(client, data);
            socket.OnMessage += (message) =>
                {
                    try
                    {
                        IPacket packet = _packetSerializer.Deserialize(message);
                        PacketRecieved(connection, packet);
                    }
                    catch (IllegalPacketException exception)
                    {
                        // If someone sent a malformed packet, close out eventually
                        Logger.Instance.Warn("{0}", exception);
                        socket.Close();
                    }

                };
        }
示例#33
0
 //Method Called when a new connection is opened to the socket server
 static void OnAdd(IWebSocketConnection conn)
 {
     try
       {
     //Send some data back to the client knows the connection is open and to prevent FF / Chrome issue with message sending
     conn.Send("OPEN");
     //Add the Socket to our list of connected sockets
     _connectedSockets.TryAdd(conn.ConnectionInfo.Id.ToString(), conn);
     //Debug messages
     if (_debugMessages) Console.WriteLine("Socket Connection Opened : " + conn.ConnectionInfo.ClientIpAddress);
       }//try
       catch (Exception ex)
       {
     //Do something with our exception
     HandleException(ex, conn);
     conn.Close(); //Connection issue so close to prevent issues
       }//catch
 }
示例#34
0
        /// <summary>
        /// When a client is connected, bind all relevant events.
        /// </summary>
        /// <param name="Socket"></param>
        private void OnClient(IWebSocketConnection Socket)
        {
            // Handle new socket opens.
            Socket.OnOpen = () =>
            {
                Console.Error.WriteLine("[II] Repeater Open:   " + Socket.ConnectionInfo.ClientIpAddress + Socket.ConnectionInfo.Path);

                try
                {
                    // Extract repeater arguments from URL.
                    var sPath = Socket.ConnectionInfo.Path.ToLowerInvariant();
                    var dArgs = Regex.Matches(sPath, "([^?=&]+)(=([^&]*))?").Cast<Match>().ToDictionary(x => x.Groups[1].Value, x => x.Groups[3].Value);

                    // Handle based on the available types.
                    if (sPath.StartsWith("/tuio"))
                    {
                        dSockets[Socket] = new TUIOForwarder(dArgs);
                    }
                    else if (sPath.StartsWith("/console"))
                    {
                        dSockets[Socket] = new ConsoleForwarder();
                    }
                    else if (sPath.StartsWith("/win7"))
                    {
                        dSockets[Socket] = new Win7Forwarder(dArgs);
                    }
                    else if (sPath.StartsWith("/win8"))
                    {
                        dSockets[Socket] = new Win8Forwarder(dArgs);
                    }
                    else if (sPath.StartsWith("/mouse"))
                    {
                        dSockets[Socket] = new MouseForwarder(dArgs);
                    }
                    else
                    {
                        throw new ArgumentException("Unsupported Repeater");
                    }
                }
                catch (Exception e)
                {
                    Console.Error.WriteLine(e.Message);
                    Socket.Close();
                }
            };

            // Handle socket closures.
            Socket.OnClose = () =>
            {
                Console.Error.WriteLine("[II] Repeater Closed: " + Socket.ConnectionInfo.ClientIpAddress + Socket.ConnectionInfo.Path);

                // Clean up.
                IForwarder pOut;
                if (dSockets.TryRemove(Socket, out pOut))
                {
                    if (pOut != null)
                        pOut.Dispose();
                }
            };

            // Handle socket errors.
            Socket.OnError = (Exception e) =>
            {
                Console.WriteLine("[WW] Repeater Socket Error: " + e.Message);
                Socket.Close();
            };

            // Listen for socket commands.
            Socket.OnMessage = (string data) =>
            {
                // Parse the message out.
                var pMessage = TouchMessage.FromString(data);
                if (pMessage.Valid == false)
                {
                    //Console.Error.WriteLine("[WW] Touch Invalid: " + data);
                    return;
                }

                // Find the forwarder.
                IForwarder pFwd;
                if (dSockets.TryGetValue(Socket, out pFwd))
                {
                    if (pFwd != null)
                        pFwd.Forward(pMessage);
                }
            };
        }
        /// <summary>
        /// Method called when the WebSocket receives a message.
        /// </summary>
        /// <param name="socket">The client socket the message comes from.</param>
        /// <param name="message">The client message.</param>
        private void OnMessage(IWebSocketConnection socket, string message)
        {
            // Timestamp containing the current time with the pattern: 2012-07-06 19:04:23
            string timestamp = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");

            // Get user id from receivedJSON object
            string uid = string.Empty;

            // The chat message object with the ts (timestamp), uid (user id) and msg (message) properties.
            ChatMessage chatMessage = new ChatMessage();

            try
            {
                if (this.connectedSockets.ContainsKey(socket))
                {
                    // Get the client user name
                    uid = this.connectedSockets[socket];

                    // Build the JSON object which will be send to all connected clients.
                    // It contains the current timestamp, the user name the message is 
                    // came from and finally the message itself.
                    chatMessage.ts = timestamp;
                    chatMessage.uid = uid;
                    chatMessage.msg = message;
                    FleckLog.Info("Msg rcv: " + uid + " @ " + timestamp + " => " + message);

                    // Socket already stored in connected sockets and send its user name. So send
                    // assembled JSON object to all connected clients.
                    foreach (KeyValuePair<Fleck.IWebSocketConnection, string> client in this.connectedSockets)
                    {
                        client.Key.Send(JsonConvert.SerializeObject(chatMessage));
                    }
                } 
                else
                {
                    // First message from the socket => message contains the client user name.
                    // Check now if user name is available. If not, add socket to the connected 
                    // sockets containing its user name.
                    if (!this.connectedSockets.ContainsValue(message))
                    {
                        // Store new connected client with its send user name to the connected sockets.
                        this.connectedSockets.Add(socket, message);
                        FleckLog.Info("Client <" + socket.ConnectionInfo.ClientIpAddress + "> set user name to <" + message + ">");
                    }
                    else
                    {
                        // Send client that the user name is already in use. The server now has
                        // to close the WebSocket to the client
                        chatMessage.ts = timestamp;
                        chatMessage.uid = message;
                        chatMessage.msg = "Error: the user name <" + message + "> is already in use!";

                        // Serialise ChatMessage object to JSON
                        socket.Send(JsonConvert.SerializeObject(chatMessage));
                        socket.Close();

                        // If socket is stored in connected sockets list, remove it
                        if (this.connectedSockets.ContainsKey(socket))
                        {
                            this.connectedSockets.Remove(socket);
                        }
                    }
                }
            }
            catch (Exception e)
            {
                // WebSocket could not be bind. E.g. if the socket is already in use.
                FleckLog.Error("Error opening WebSocket on <" + this.connectionInfo + ">. WebSocket maybe in use?");
                FleckLog.Error("Exception string: \n" + e.ToString());

                // Wait until key is pressed
                Console.ReadLine();

                // Close application
                System.Environment.Exit(-1);
            }
        }
示例#36
0
        private void OnConnected(IWebSocketConnection context)
        {
            if (UserList.Count < ClientLimit)
            {
                Debug.WriteLine($"OnConnected: {context.ConnectionInfo.Id}, {context.ConnectionInfo.ClientIpAddress}");

                UserList[context.ConnectionInfo.Id] = context;
            }
            else
            {
                Debug.WriteLine($"OverLimit, Closed: {context.ConnectionInfo.Id}, {context.ConnectionInfo.ClientIpAddress}");
                context.Close();
            }
        }
示例#37
0
        private void OnReceive(IWebSocketConnection context, string msg)
        {
            Debug.WriteLine($"OnReceive {context.ConnectionInfo.Id}: {msg}");

            if (!msg.Contains("command")) return; 

            if(UserList.ContainsKey(context.ConnectionInfo.Id))
            {
                JsonData msgJson = JsonMapper.ToObject(msg);
                string command = msgJson["command"].ToString();

                switch (command) 
                {
                    case offer:
                    {
                        if (UserList.Count <= ClientLimit && !Streams.ContainsKey(context.ConnectionInfo.Id))
                        {
                            var session = Streams[context.ConnectionInfo.Id] = new WebRtcSession();
                            {
                                using (var go = new ManualResetEvent(false))
                                {
                                    var t = Task.Factory.StartNew(() =>
                                    {
                                        ManagedConductor.InitializeSSL();

                                        using (session.WebRtc)
                                        {
                                            session.WebRtc.AddServerConfig("stun:stun.l.google.com:19302", string.Empty, string.Empty);
                                            session.WebRtc.AddServerConfig("stun:stun.anyfirewall.com:3478", string.Empty, string.Empty);
                                            session.WebRtc.AddServerConfig("stun:stun.stunprotocol.org:3478", string.Empty, string.Empty);
                                            //session.WebRtc.AddServerConfig("turn:127.0.0.1:444", "test", "test");

                                            var ok = session.WebRtc.InitializePeerConnection();
                                            if (ok)
                                            {
                                                go.Set();

                                                // does not work yet, javascript side works though ;/
                                                //session.WebRtc.CreateDataChannel("msgDataChannel");

                                                while (!session.Cancel.Token.IsCancellationRequested &&
                                                       session.WebRtc.ProcessMessages(1000))
                                                {
                                                    Debug.Write(".");
                                                }
                                                session.WebRtc.ProcessMessages(1000);
                                            }
                                            else
                                            {
                                                Debug.WriteLine("InitializePeerConnection failed");
                                                context.Close();
                                            }
                                        }
                                        
                                    }, session.Cancel.Token, TaskCreationOptions.LongRunning, TaskScheduler.Default);

                                    if (go.WaitOne(9999))
                                    {
                                        session.WebRtc.OnIceCandidate += delegate (string sdp_mid, int sdp_mline_index, string sdp)
                                        {
                                            if (context.IsAvailable)
                                            {
                                                JsonData j = new JsonData();
                                                j["command"] = "OnIceCandidate";
                                                j["sdp_mid"] = sdp_mid;
                                                j["sdp_mline_index"] = sdp_mline_index;
                                                j["sdp"] = sdp;
                                                context.Send(j.ToJson());
                                            }
                                        };

                                        session.WebRtc.OnSuccessAnswer += delegate(string sdp)
                                        {
                                            if (context.IsAvailable)
                                            {
                                                JsonData j = new JsonData();
                                                j["command"] = "OnSuccessAnswer";
                                                j["sdp"] = sdp;
                                                context.Send(j.ToJson());
                                            }
                                        };

                                        session.WebRtc.OnFailure += delegate(string error)
                                        {
                                            Trace.WriteLine($"OnFailure: {error}");
                                        };

                                        session.WebRtc.OnError += delegate
                                        {
                                            Trace.WriteLine("OnError");
                                        };

                                        unsafe
                                        {
                                            session.WebRtc.OnFillBuffer += delegate (byte * frame_buffer, uint yuvSize)
                                            {
                                                OnFillBuffer(frame_buffer, yuvSize);
                                            };

                                            session.WebRtc.OnRenderRemote += delegate (byte* frame_buffer, uint w, uint h)
                                            {
                                                OnRenderRemote(frame_buffer, w, h);
                                            };
                                        }

                                        var d = msgJson["desc"];
                                        var s = d["sdp"].ToString();

                                        session.WebRtc.OnOfferRequest(s);
                                    }
                                }
                            }
                        }
                    }
                    break;

                    case onicecandidate:
                    {
                        var c = msgJson["candidate"];

                        var sdpMLineIndex = (int)c["sdpMLineIndex"];
                        var sdpMid = c["sdpMid"].ToString();
                        var candidate = c["candidate"].ToString();

                        var session = Streams[context.ConnectionInfo.Id];
                        {
                            session.WebRtc.AddIceCandidate(sdpMid, sdpMLineIndex, candidate);
                        }
                    }
                    break;
                }
            }
        }
示例#38
0
        internal void MessageRPCClientConnection(IWebSocketConnection webSocket, string message, KeePassRPCService service)
        {
            KeePassRPCClientConnection connection = null;

            lock (_lockRPCClientManagers)
            {
                _lockRPCClientManagers.HeldBy = Thread.CurrentThread.ManagedThreadId;
                foreach (KeePassRPCClientManager manager in _RPCClientManagers.Values)
                {
                    foreach (KeePassRPCClientConnection conn in manager.CurrentRPCClientConnections)
                    {
                        if (conn.WebSocketConnection == webSocket)
                        {
                            connection = conn;
                            break;
                        }
                    }
                    if (connection != null)
                        break;
                }
            }

            if (connection != null)
                connection.ReceiveMessage(message, service);
            else
                webSocket.Close();
        }