/// <summary>
 /// Called to notify of a new connection
 /// </summary>
 /// <param name="socket"></param>
 public void Connected(WebSocket socket)
 {
     socket.ConnectionClosed += OnConnectionClosed;
     RpcConnection connection = new RpcConnection(socket);
     lock (this)
     {
         m_connections.Add(socket, connection);
     }
 }
Example #2
0
 /// <summary>
 /// Constructor with a socket
 /// </summary>
 /// <param name="socket"></param>
 public RpcConnection(WebSocket socket)
 {
     m_socket = socket;
     m_authenticated = false;
     // Get references to the core components we need
     m_builder = new MessageBuilder();
     m_messagebus = Locator.Current.GetService<IMessageBus>();
     m_mot = Locator.Current.GetService<MasterObjectTable>();
     // Listen for incoming messages
     m_socket.DataReceived += OnDataReceived;
 }
 /// <summary>
 /// Close the connection
 /// </summary>
 /// <param name="socket"></param>
 void OnConnectionClosed(WebSocket socket)
 {
     RpcConnection connection = null;
     lock (this)
     {
         if (!m_connections.ContainsKey(socket))
             return;
         connection = m_connections[socket];
         m_connections.Remove(socket);
     }
     connection.Close();
 }
Example #4
0
        private async void _webSockets_MessageRecived(string guid, WebSocket socket, string message)
        {
            try
            {
                var recivedData = DeserializeObject<ServerMessage>(message);
                await ProcessMessage(guid, recivedData);
                
            }
            catch (JsonReaderException e)
            {
                var messageErr = new ServerMessage()
                {
                    ClientID = guid,
                    Command = "Error",
                    Value = "Wrong message's format"
                };
                _webSockets.SendMessage(guid, messageErr);

            }
        }
Example #5
0
        public void Connected(WebSocket socket)
        {
            var guid = Guid.NewGuid().ToString();
            _webSockets.Add(guid, socket);
            

            socket.DataReceived += (webSocket, frame) => MessageRecived?.Invoke(_webSockets.First(x => x.Value == webSocket).Key,webSocket, frame);
            socket.ConnectionClosed += (webSocket) =>
            {
                var connection = _webSockets.First(s => s.Value == webSocket);
                _webSockets.Remove(connection.Key);
            };

            if (_portMappings.IsBindingPosible())
            {
                _portMappings.Bind(guid);

                var message = new ServerMessage()
                {
                    ClientID = guid,
                    Command = "Init",
                    Value = _portMappings.CheckBinding(guid).ToString()
                };
                SendMessage(guid, message);
            }
            else
            {
                var message = new ServerMessage()
                {
                    ClientID = guid,
                    Command = "Init",
                    Value = "Max Number Of Clients Reached. Please close connection"
                };
                SendMessage(guid, message);
            }

            
        }
Example #6
0
        /// <summary>
        /// Handle the HTTP connection
        /// 
        /// This implementation doesn't support keep alive so each HTTP session
        /// consists of parsing the request, dispatching to a handler and then
        /// sending the response before closing the connection.
        /// </summary>
        /// <param name="server"></param>
        /// <param name="input"></param>
        /// <param name="output"></param>
        public void ProcessHttpRequest(Stream input, Stream output)
		{
            // Set up state
            HttpRequest request = null;
            HttpResponse response = null;
            HttpException parseError = null;
            // Process the request
            try
            {
                request = ParseRequest(input);
                if ((request == null) || !m_connected)
                    return; // Nothing we can do, just drop the connection
                // Do we have any content in the body ?
                if (request.Headers.ContainsKey(HttpHeaders.ContentType))
                {
                    if (!request.Headers.ContainsKey(HttpHeaders.ContentLength))
                        throw new HttpLengthRequiredException();
                    int length;
                    if (!int.TryParse(request.Headers[HttpHeaders.ContentLength], out length))
                        throw new HttpLengthRequiredException();
                    request.ContentLength = length;
                    if (length > MaxRequestBody)
                        throw new HttpRequestEntityTooLargeException();
                    // Read the data in
                    MemoryStream content = new MemoryStream();
                    while (m_connected && (content.Length != length))
                    {
                        ReadData(input);
                        content.Write(m_buffer, 0, m_index);
                        ExtractBytes(m_index);
                    }
                    // Did the connection drop while reading?
                    if (!m_connected)
                        return;
                    // Reset the stream location and attach it to the request
                    content.Seek(0, SeekOrigin.Begin);
                    request.Content = content;
                }
                // Process the cookies
				if (request.Headers.ContainsKey(HttpHeaders.Cookie))
				{
					string[] cookies = request.Headers[HttpHeaders.Cookie].Split(CookieSeparator);
					foreach (string cookie in cookies)
					{
						string[] parts = cookie.Split(CookieValueSeparator);
						Cookie c = new Cookie();
						c.Name = parts[0].Trim();
						if (parts.Length > 1)
							c.Value = parts[1].Trim();
						request.Cookies.Add(c);
					}
				}
				// We have at least a partial request, create the matching response
				HttpContext context = new HttpContext();
				response = new HttpResponse();
				// Apply filters
                m_server.ApplyFilters(request, response, context);
                // TODO: Check for WebSocket upgrade
				IWebSocketRequestHandler wsHandler = UpgradeToWebsocket(request, response);
				if (wsHandler!=null)
				{
					// Write the response back to accept the connection
					response.Send(output);
					output.Flush();
					// Now we can process the websocket
					WebSocket ws = new WebSocket(input, output);
					wsHandler.Connected(ws);
					ws.Run();
					// Once the websocket connection is finished we don't need to do anything else
					return;
				}
				// Dispatch to the handler
				string partialUri;
				IHttpRequestHandler handler = m_server.GetHandlerForUri(request.URI, out partialUri);
				if (handler == null)
					throw new HttpNotFoundException();
				handler.HandleRequest(partialUri, request, response, context);
            }
            catch (HttpException ex)
            {
                parseError = ex;
            }
            catch (Exception)
            {
                parseError = new HttpInternalServerErrorException();
            }
            // Do we need to send back an error response ?
            if (parseError != null)
            {
                // TODO: Clear any content that might already be added
                response.ResponseCode = parseError.ResponseCode;
                response.ResponseMessage = parseError.Message;
            }
            // Write the response
            response.Send(output);
            output.Flush();
        }
Example #7
0
 void OnDataReceived(WebSocket socket, string frame)
 {
     socket.Send(frame);
 }
Example #8
0
 public void Connected(WebSocket socket)
 {
     socket.DataReceived += OnDataReceived;
 }
Example #9
0
 /// <summary>
 /// Invoked when a new frame is recieved from the client
 /// </summary>
 /// <param name="socket"></param>
 /// <param name="frame"></param>
 void OnDataReceived(WebSocket socket, string frame)
 {
     // Decode the frame
     IDictionary<string, object> data = ObjectPacker.UnpackRaw(frame);
     if (data == null)
         return;
     // Is it a message ?
     if (ContainsKeys(data, MessageTopic, MessagePayload))
         ProcessMessage(data);
     else if (ContainsKeys(data, FunctionSequence, FunctionName, FunctionParameters))
         ProcessRpcCall(data);
 }