Inheritance: IDisposable
Exemplo n.º 1
0
 public override void HandlePacket(Packet packet)
 {
     _client = packet.Client;
     _authClient = packet.AuthClient;
     _packet = packet;
     _builder = new MessageBuilder(_authClient, _client, _packet.EndPoint, _packet.SyncKey);
     switch (_packet.PacketType)
     {
         case PacketManager.PacketTypes.AddOrUpdateJob:
             AddOrUpdateJob();
             break;
         case PacketManager.PacketTypes.RemoveJob:
             RemoveJob();
             break;
         case PacketManager.PacketTypes.StopJobDaemon:
             StopJobDaemon();
             break;
         case PacketManager.PacketTypes.StartJobDaemon:
             StartJobDaemon();
             break;
         case PacketManager.PacketTypes.GetJobDaemonStatus:
             GetJobDaemonStatus();
             break;
         case PacketManager.PacketTypes.GetJobContents:
             GetJobContents();
             break;
         case PacketManager.PacketTypes.GetAllJobs:
             GetAllJobs();
             break;
        
     }
 }
Exemplo n.º 2
0
 public MessageBuilder(AuthClient authClient, WebSocket client, string endpoint, string syncKey)
 {
     _authClient = authClient;
     _client = client;
     Endpoint = endpoint;
     synckey = syncKey;
 }
Exemplo n.º 3
0
        public void AcceptMessage(WebSocket ws, Dictionary<string, dynamic> msgDict)
        {
            string msg = JsonConvert.SerializeObject(msgDict, Formatting.None);
            this.messagelog += msg + "\n";

            // Check if message is for server.
            if (msgDict["msgType"] == "CreatureDied")
            {
                // Not doing anything with this yet.
            }
            else if (msgDict["msgType"] == "LifeReduced")
            {
                // Find the match and report that the ws said something about a reduced life.
                this.LifeReduced(ws);
            }
            else if (msgDict["msgType"] == "RequestEntity")
            {
                // Find related match, relay message.
                this.SendToOpponent(ws, msg);
                int type = (int)msgDict["type"];
                int x = (int)msgDict["location"]["x"];
                int y = (int)msgDict["location"]["y"];
                int parentId = (int)msgDict["parent_id"];
                this.EntityRequested(ws, type, x, y, parentId);
            }
            else
            {
                // Find related match, relay message.
                this.SendToOpponent(ws, msg);
            }
        }
Exemplo n.º 4
0
        public GameServerConnection(vtortola.WebSockets.WebSocket socket)
        {
            Socket  = socket;
            isReady = true;

            SetupLoginHandler();
        }
 public WebSocketHandler(IServiceBus bus, WebSocket ws, IEventSerializator serializer, ILogger log)
 {
     _ws = ws;
     _queue = bus;
     _log = log;
     _serializer = serializer;
 }
Exemplo n.º 6
0
        public ClientConnection(vtortola.WebSockets.WebSocket socket)
        {
            Socket  = socket;
            isReady = true;

            SetupLoginHandler();
        }
Exemplo n.º 7
0
        /// <inheritdoc />
        public async Task ConnectAsync(ISession session, CancellationToken ct = default(CancellationToken),
                                       bool appearOnline = false, int connectTimeout = 5000)
        {
            if (_listener != null)
            {
                await _listener.CloseAsync();

                _messageReplies.Clear();
                _listener.Dispose();
                _listener = null;
            }

            var addr = new UriBuilder(_baseUri)
            {
                Path  = "/ws",
                Query = string.Concat("lang=en&status=", appearOnline, "&token=", session.AuthToken)
            };

            var timeoutTask = Task.Delay(TimeSpan.FromMilliseconds(connectTimeout), ct);
            var connectTask = _client.ConnectAsync(addr.Uri, ct);

            // Limit time (msec) allowed for connect attempts.
            if (await Task.WhenAny(connectTask, timeoutTask).ConfigureAwait(false) == timeoutTask)
            {
                throw new TimeoutException($"Socket connect timed out after '{connectTimeout}' milliseconds.");
            }

            _listener = await connectTask.ConfigureAwait(false);

            ReadSocketAsync(ct);
            WriteSocketAsync(ct);
        }
 public string Login(string password, WebSocket clientSocket)
 {
     var code = 3;
     if (string.IsNullOrEmpty(password))
     {
         code = INVALID_PASSWORD;
     }
     using (var context = new PrincipalContext(ContextType.Machine))
     {
         code = context.ValidateCredentials(GetUsername(), password) ? 2 : 3;
     }
     var authenticated = code == AUTHENTICATED;
     foreach (var client in TaskManagerServer.AllClients.Where(client => client.Value.Client == clientSocket))
     {
         if (code == INVALID_PASSWORD)
         {
             client.Value.Authenticated = false;
         }
         else if (code == AUTHENTICATED)
         {
             client.Value.Authenticated = true;
         }
     }
     var authenticationData = new JavaScriptSerializer().Serialize(new
     {
         endpoint = "authentication",
         results = new
         {
             authenticated,
             message = authenticated ? "Login was successfull" : "Login was unsuccessful"
         }
     });
     return authenticationData;
 }
        private async Task HandleWebSocketAsync(WebSocket websocket)
        {
            try
            {
                if (OnConnect != null)
                    OnConnect.Invoke(websocket);

                while (websocket.IsConnected)
                {
                    var message = await websocket.ReadStringAsync(CancellationToken.None)
                                                 .ConfigureAwait(false);
                    if (message != null && OnMessage != null)
                        OnMessage.Invoke(websocket, message);
                }

                if (OnDisconnect != null)
                    OnDisconnect.Invoke(websocket);
            }
            catch (Exception ex)
            {
                if (OnError != null)
                    OnError.Invoke(websocket, ex);
            }
            finally
            {
                websocket.Dispose();
            }
        }
		private async void ListenForMessages(WebSocket socket)
		{
			TOP:
			try
			{
				if (!socket.IsConnected)
					return;

				var message = await socket.ReadMessageAsync(_tokenSource.Token);
				if (message != null)
				{
					using (var ms = new MemoryStream()) // length was throwing an exception
					{
						message.CopyTo(ms);
						var segment = new ArraySegment<byte>(ms.GetBuffer(), 0, (int)ms.Length);
						var args = new DataReceivedArgs { Data = segment, SessionID = socket };
						Received.Invoke(this, args);
					}
				}
				goto TOP;
			}
			catch (TaskCanceledException) { }
			catch (Exception)
			{
				goto TOP;
			}
		}
Exemplo n.º 11
0
 public WebSocketHandler(IServiceBus bus, WebSocket ws, IEventSerializator serializer, ILogger log)
 {
     _ws = ws;
     _queue = bus;
     _log = log;
     _serializer = serializer;
     TerminalClients = new ConcurrentDictionary<string, AuthClient>();
 }
Exemplo n.º 12
0
        private void Disconnect()
        {
            _websocket?.Dispose();
            _websocket = null;

            _websocketHandle?.Dispose();
            _websocketHandle = null;
        }
 static Guid GetSessionId(WebSocket ws)
 {
     Guid sessionId = Guid.Empty;
     Cookie cookie = ws.HttpRequest.Cookies[ConnectionManager.UserSessionCookieName] ?? ws.HttpResponse.Cookies[ConnectionManager.UserSessionCookieName];
     if (cookie != null && Guid.TryParse(cookie.Value, out sessionId))
         return sessionId;
     else
         throw new Exception("No session ID generated for this connection");
 }
Exemplo n.º 14
0
 public Player(WebSocket ws, String username, String uniqueId)
 {
     // TODO: Actually write code that'll connect to a DB to see if we can pull rating information.
     this.ws = ws;
     this.username = username;
     this.uniqueId = uniqueId;
     this.rating = 0;
     this.currentMatch = null;
 }
Exemplo n.º 15
0
 public static Guid GetConnectionId(WebSocket clientSocket)
 {
     Guid connectionId;
     var cookie = clientSocket.HttpRequest.Cookies["ConnectionId"] ??
                  clientSocket.HttpResponse.Cookies["ConnectionId"];
     if (cookie == null || !Guid.TryParse(cookie.Value, out connectionId))
         return Guid.Empty;
     return connectionId;
 }
        private bool CanAcceptConnection(WebSocket con)
        {
            if (String.IsNullOrEmpty(_ipAddressStart))
                return true;

            if (IPAddress.IsLoopback(con.RemoteEndpoint.Address))
                return true;

            return con.RemoteEndpoint.Address.ToString().StartsWith(_ipAddressStart);
        }
Exemplo n.º 17
0
 private static void HandleMessage(WebSocket websocket, string message)
 {
     foreach (var apiController in
         ApiControllers.Select(controller => controller.Value)
             .Where(apiController => apiController.Client == websocket))
     {
         var packet = new Packets(message);
         apiController.HandlePacket(packet);
     }
 }
 internal ServerWebSocketTransport(vtortola.WebSockets.WebSocket webSocket, IEnvelopeSerializer envelopeSerializer, ITraceWriter traceWriter = null)
 {
     if (webSocket == null)
     {
         throw new ArgumentNullException(nameof(webSocket));
     }
     _webSocket          = webSocket;
     _envelopeSerializer = envelopeSerializer;
     _traceWriter        = traceWriter;
     _receiveSemaphore   = new SemaphoreSlim(1);
     _sendSemaphore      = new SemaphoreSlim(1);
 }
Exemplo n.º 19
0
 /// <summary>
 ///     Create a packet
 /// </summary>
 /// <param name="authClient"></param>
 /// <param name="client"></param>
 /// <param name="endPoint"></param>
 /// <param name="syncKey"></param>
 /// <param name="args"></param>
 /// <param name="packetType"></param>
 /// <param name="packetHandler"></param>
 public Packet(AuthClient authClient, WebSocket client, string endPoint, string syncKey, List<object> args,
     PacketTypes packetType,
     Type packetHandler)
 {
     AuthClient = authClient;
     Client = client;
     EndPoint = endPoint;
     SyncKey = syncKey;
     Args = args;
     PacketType = packetType;
     _packetHandler = packetHandler;
 }
Exemplo n.º 20
0
 public override void HandlePacket(Packet packet)
 {
     _client = packet.Client;
     _authClient = packet.AuthClient;
     _packet = packet;
     _builder = new MessageBuilder(_authClient, _client, _packet.EndPoint, _packet.SyncKey);
     switch (_packet.PacketType)
     {
         case PacketManager.PacketTypes.RequestCpuInformation:
             GetCpuInformation();
             break;
     }
 }
Exemplo n.º 21
0
 private static void HandleDisconnect(WebSocket clientSocket)
 {
     foreach (var client in AllClients)
     {
         if (client.Value.Client != clientSocket) continue;
         AuthClient temp = null;
         ApiController temp2 = null;
         AllClients.TryRemove(client.Key, out temp);
         ApiControllers.TryRemove(client.Key, out temp2);
         Console.WriteLine("Disconnection from " + clientSocket.RemoteEndpoint);
         Console.WriteLine(ApiControllers.Count);
     }
 }
Exemplo n.º 22
0
        internal void Open(IDisposable websocketHandle, WebSocket websocket, CancellationToken cancellationToken)
        {
            if (websocketHandle == null)
                throw new ArgumentNullException(nameof(websocketHandle));

            if (websocket == null)
                throw new ArgumentNullException(nameof(websocket));

            _websocketHandle = websocketHandle;
            _websocket = websocket;

            ReadWebSocketAsync(cancellationToken);
            WriteWebSocketAsync(cancellationToken);
        }
Exemplo n.º 23
0
 private static void HandleConnect(WebSocket clientSocket)
 {
     Console.WriteLine("Connection from " + clientSocket.RemoteEndpoint);
     var client = new AuthClient(clientSocket);
     var apiController = new ApiController(clientSocket)
     {
         //set the auth Client so we can use it later
         authClient = client
     };
     AllClients.AddOrUpdate(client.GetHashCode().ToString(), client, (key, value) => value);
     ApiControllers.AddOrUpdate(apiController.authClient.GetHashCode().ToString(), apiController,
         (key, value) => value);
     SendWelcomeMessage(clientSocket);
 }
Exemplo n.º 24
0
 public override void HandlePacket(Packet packet)
 {
     _client = packet.Client;
     _authClient = packet.AuthClient;
     _packet = packet;
     _builder = new MessageBuilder(_authClient, _client, _packet.EndPoint, _packet.SyncKey);
     switch (_packet.PacketType)
     {
         case PacketManager.PacketTypes.InvalidOrEmptyPacket:
             InvalidPacket();
             break;
         case PacketManager.PacketTypes.NoAuth:
             NoAuth();
             break;
     }
 }
Exemplo n.º 25
0
 public override void HandlePacket(Packet packet)
 {
     _client = packet.Client;
     _authClient = packet.AuthClient;
     _packet = packet;
     _builder = new MessageBuilder(_authClient, _client, _packet.EndPoint, _packet.SyncKey);
     switch (_packet.PacketType)
     {
         case PacketManager.PacketTypes.SaveSettings:
             SaveSettings();
             break;
         case PacketManager.PacketTypes.GetCurrentSettings:
             GetCurrentSettings();
             break;
     }
 }
Exemplo n.º 26
0
        private static async Task EchoAllIncomingMessagesAsync(WebSocket webSocket, CancellationToken cancellation)
        {
            Console.WriteLine("Client '" + webSocket.RemoteEndpoint + "' connected.");
            var sw = new Stopwatch();

            try
            {
                while (webSocket.IsConnected && !cancellation.IsCancellationRequested)
                {
                    try
                    {
                        var messageText = await webSocket.ReadStringAsync(cancellation).ConfigureAwait(false);

                        if (messageText == null)
                        {
                            break; // webSocket is disconnected
                        }
                        Console.WriteLine("Client '" + webSocket.RemoteEndpoint + "' recived: " + messageText + ".");

                        sw.Restart();

                        messageText = WebSocketHandler(messageText);

                        await webSocket.WriteStringAsync(messageText, cancellation).ConfigureAwait(false);

                        Console.WriteLine("Client '" + webSocket.RemoteEndpoint + "' sent: " + messageText + ".");

                        sw.Stop();
                    }
                    catch (TaskCanceledException)
                    {
                        break;
                    }
                    catch (Exception readWriteError)
                    {
                        Console.WriteLine("An error occurred while reading/writing echo message.", readWriteError);
                        await webSocket.CloseAsync().ConfigureAwait(false);
                    }
                }
            }
            finally
            {
                webSocket.Dispose();
                Console.WriteLine("Client '" + webSocket.RemoteEndpoint + "' disconnected.");
            }
        }
Exemplo n.º 27
0
 public async void PushBinary(WebSocket client, string endpoint, string syncKey, byte[] data)
 {
     try
     {
         using (var messageWriter = client.CreateMessageWriter(WebSocketMessageType.Binary))
         {
             using (var stream = new MemoryStream(data))
             {
                 await stream.CopyToAsync(messageWriter);
             }
         }
     }
     catch (Exception)
     {
         //should never happen
     }
 }
Exemplo n.º 28
0
 public override void HandlePacket(Packet packet)
 {
     _client = packet.Client;
     _authClient = packet.AuthClient;
     _packet = packet;
     _builder = new MessageBuilder(_authClient, _client, _packet.EndPoint, _packet.SyncKey);
     switch (_packet.PacketType)
     {
         case PacketManager.PacketTypes.RequestOsInformation:
             GetOperatingSystemInformation();
             break;
       
         case PacketManager.PacketTypes.GetEventLogs:
             // GetEventLogs();
             break;
     }
 }
Exemplo n.º 29
0
        public async void EntityRequested(WebSocket ws, int EntityType, int x, int y, int parentId)
        {
            this.entityCounter++;
            int delay = 0;
            if (ws == this.attacker.getSocket())
            {
                delay = Match.AttackerDelay;
            }
            else
            {
                delay = Match.DefenderDelay;
            }

            await Task.Delay(delay);
            MsgObjects.NewEntity temp = new MsgObjects.NewEntity(EntityType, this.entityCounter, x, y, parentId);
            this.SendMessage(null, temp.ToJSON());
        }
        private async Task <bool> InternalAssertConnected(CancellationToken cancellationToken)
        {
            if (this.client != null &&
                this.wsClient != null &&
                this.wsClient.IsConnected &&
                !this.receiveMessagesCts.IsCancellationRequested)
            {
                Logger.Trace("Already connected");
                return(false);
            }

            var retryCount = 0;

            do
            {
                try
                {
                    this.receiveMessagesCts.Cancel();
                    await this.messageLoopTask;
                    Logger.Trace("Message loop task finished");
                    this.receiveMessagesCts = new CancellationTokenSource();

                    this.client   = new WebSocketClient(this.options);
                    this.wsClient = await this.client.ConnectAsync(this.Endpoint, cancellationToken);

                    this.messageLoopTask = Task.Run(() => ReceiveMessagesLoop(this.receiveMessagesCts.Token), cancellationToken);

                    Logger.Log("Connected to server");
                    return(true);
                }
                catch (OperationCanceledException)
                {
                    throw;
                }
                catch (Exception ex)
                {
                    Logger.Warn($"Connection failed, retry {++retryCount}/10");
                    Logger.Debug($"{ex}");
                    await Task.Delay(2000, cancellationToken);
                }
            } while (retryCount < 10);

            throw new WebsocketConnectionFailedException();
        }
        private Boolean TryAddWebSocketToPool(WebSocket con)
        {
            try
            {
                _semaphore.EnterWriteLock();

                if (_connections.Count >= _maxConnectedClients)
                   return false;

                var ws = new WebSocketWrapper(con);
                _connections.Add(ws);
                Task.Run(() => AcceptWebSocketCommands(ws));
                return true;
            }
            finally
            {
                _semaphore.ExitWriteLock();
            } 
        }
Exemplo n.º 32
0
        public void Serialize(WebSocket client, string endpoint, string syncKey, object data, bool binary = false)
        {
            var serializer = new JavaScriptSerializer {MaxJsonLength = int.MaxValue};
            var json = serializer.Serialize(new
            {
                endpoint,
                syncKey,
                results = data
            });


            if (binary)
            {
                PushFile(client, "");
            }
            else
            {
                Push(client, json);
            }
        }
Exemplo n.º 33
0
        private async void ReadSocketAsync(CancellationToken ct)
        {
            try
            {
                OnConnect?.Invoke(this, EventArgs.Empty);

                while (!ct.IsCancellationRequested && _listener.IsConnected)
                {
                    var readStream = await _listener.ReadMessageAsync(ct).ConfigureAwait(false);

                    if (readStream == null)
                    {
                        continue; // NOTE does stream need to be consumed?
                    }

                    using (var reader = new StreamReader(readStream, true))
                    {
                        var message = await reader.ReadToEndAsync().ConfigureAwait(false);

                        if (Trace)
                        {
                            Logger.DebugFormat("Socket read message: '{0}'", message);
                        }

                        var envelope = message.FromJson <WebSocketMessageEnvelope>();
                        ProcessMessageAsync(envelope, message);
                    }
                }

                OnDisconnect?.Invoke(this, EventArgs.Empty);
            }
            catch (OperationCanceledException e)
            {
                if (Trace)
                {
                    Logger.DebugFormat("Socket operation cancelled: '{0}'", e.Message);
                }
                _listener.Dispose();
                _listener = null;
            }
        }
Exemplo n.º 34
0
 public override void HandlePacket(Packet packet)
 {
     _client = packet.Client;
     _authClient = packet.AuthClient;
     _packet = packet;
     _builder = new MessageBuilder(_authClient, _client, _packet.EndPoint, _packet.SyncKey);
     switch (_packet.PacketType)
     {
         case PacketManager.PacketTypes.ChangeDisplayResolution:
             ChangeScreenResolution();
             break;
         case PacketManager.PacketTypes.RotateDisplay:
             RotateDisplay();
             break;
         case PacketManager.PacketTypes.SetPrimaryDisplay:
             SetPrimaryDisplay();
             break;
         case PacketManager.PacketTypes.GetEventLogs:
             // GetEventLogs();
             break;
     }
 }
Exemplo n.º 35
0
		static async Task HandleConnectionAsync(WebSocket ws, CancellationToken cancellation)
		{
			try
			{
				while (ws.IsConnected && !cancellation.IsCancellationRequested)
				{
					String msg = await ws.ReadStringAsync(cancellation).ConfigureAwait(false);
					Log("Message: " + msg);
					ws.WriteString(msg);
				}
			}
			catch (Exception aex)
			{
				Log("Error Handling connection: " + aex.GetBaseException().Message);
				try { ws.Close(); }
				catch { }
			}
			finally
			{
				ws.Dispose();
			}
		}
 private static void DisconnectWebSocket(WebSocket con)
 {
     Task.Run(() => con.Dispose());
 }
Exemplo n.º 37
-1
 public async void PushFile(WebSocket client, string filePath)
 {
     using (var messageWriter = client.CreateMessageWriter(WebSocketMessageType.Binary))
     using (var fs = new FileStream(filePath, FileMode.Open, FileAccess.Read))
     {
         await fs.CopyToAsync(messageWriter);
     }
 }