Exemple #1
0
 private static void newListenerInstance_ConnectionReceived(StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args)
 {
     try
     {
         var newConnectionInfo = new ConnectionInfo(true, ConnectionType.TCP, new IPEndPoint(IPAddress.Parse(args.Socket.Information.RemoteAddress.DisplayName.ToString()), int.Parse(args.Socket.Information.RemotePort)));
         TCPConnection.GetConnection(newConnectionInfo, NetworkComms.DefaultSendReceiveOptions, args.Socket, true);
     }
     catch (ConfirmationTimeoutException)
     {
         //If this exception gets thrown its generally just a client closing a connection almost immediately after creation
     }
     catch (CommunicationException)
     {
         //If this exception gets thrown its generally just a client closing a connection almost immediately after creation
     }
     catch (ConnectionSetupException)
     {
         //If we are the server end and we did not pick the incoming connection up then tooo bad!
     }
     catch (SocketException)
     {
         //If this exception gets thrown its generally just a client closing a connection almost immediately after creation
     }
     catch (Exception ex)
     {
         //For some odd reason SocketExceptions don't always get caught above, so another check
         if (ex.GetBaseException().GetType() != typeof(SocketException))
         {
             //Can we catch the socketException by looking at the string error text?
             if (ex.ToString().StartsWith("System.Net.Sockets.SocketException"))
             {
                 NetworkComms.LogError(ex, "ConnectionSetupError_SE");
             }
             else
             {
                 NetworkComms.LogError(ex, "ConnectionSetupError");
             }
         }
     }
 }
Exemple #2
0
        /// <summary>
        /// Returns true if all the servers (TCP and UDP) could be started. Writes to the log on both failure and success.
        /// </summary>
        /// <returns></returns>
        public async Task <bool> StartAsync()
        {
            var retval = true;

            TcpListener = new StreamSocketListener();
            TcpListener.ConnectionReceived += Listener_ConnectionReceived;
            try
            {
                await TcpListener.BindServiceNameAsync(Options.Service);

                {
                    Log($"Time Connected on Tcp {TcpListener.Information.LocalPort}");
                }
            }
            catch (Exception e)
            {
                Stats.NExceptions++;
                Log($"ERROR: unable to start TCP server {e.Message}");
                retval = false;
            }

            UdpListener = new DatagramSocket();
            UdpListener.MessageReceived += UdpListener_MessageReceived;
            try
            {
                await UdpListener.BindServiceNameAsync(Options.Service);

                {
                    Log($"Time Connected on Udp {UdpListener.Information.LocalPort}");
                }
            }
            catch (Exception e)
            {
                Stats.NExceptions++;
                Log($"ERROR: unable to start UDP server {e.Message}");
                retval = false;
            }

            return(retval);
        }
Exemple #3
0
        private async Task InitializeRfcommServer()
        {
            try
            {
                m_rfcommService = await RfcommServiceProvider.CreateAsync(RfcommServiceId.FromUuid(ServiceUuid));
            }
            catch (Exception ex) when((uint)ex.HResult == 0x800710DF)
            {
                // Catch exception HRESULT_FROM_WIN32(ERROR_DEVICE_NOT_AVAILABLE).
                return;
            }

            m_socketListener = new StreamSocketListener();
            m_socketListener.ConnectionReceived += OnConnectionReceivedAsync;
            var rfcomm = m_rfcommService.ServiceId.AsString();

            await m_socketListener.BindServiceNameAsync(
                m_rfcommService.ServiceId.AsString(),
                SocketProtectionLevel.BluetoothEncryptionAllowNullAuthentication);

            var sdpWriter = new DataWriter
            {
                UnicodeEncoding = UnicodeEncoding.Utf8
            };

            sdpWriter.WriteByte(SdpServiceNameAttributeType);
            sdpWriter.WriteByte((byte)SdpServiceName.Length);
            sdpWriter.WriteString(SdpServiceName);

            m_rfcommService.SdpRawAttributes.Add(SdpServiceNameAttributeId, sdpWriter.DetachBuffer());

            try
            {
                m_rfcommService.StartAdvertising(m_socketListener, true);
            }
            catch (Exception ex)
            {
                Debug.Write(ex);
            }
        }
Exemple #4
0
        /// <summary>
        /// This is the click handler for the 'CloseSockets' button.
        /// </summary>
        /// <param name="sender">Object for which the event was generated.</param>
        /// <param name="e">Event's parameters.</param>
        private void CloseSockets_Click(object sender, RoutedEventArgs e)
        {
            object outValue;

            if (CoreApplication.Properties.TryGetValue("clientDataWriter", out outValue))
            {
                // Remove the data writer from the list of application properties as we are about to close it.
                CoreApplication.Properties.Remove("clientDataWriter");
                DataWriter dataWriter = (DataWriter)outValue;

                // To reuse the socket with other data writer, application has to detach the stream from the writer
                // before disposing it. This is added for completeness, as this sample closes the socket in
                // very next block.
                dataWriter.DetachStream();
                dataWriter.Dispose();
            }

            if (CoreApplication.Properties.TryGetValue("clientSocket", out outValue))
            {
                // Remove the socket from the list of application properties as we are about to close it.
                CoreApplication.Properties.Remove("clientSocket");
                StreamSocket socket = (StreamSocket)outValue;
                socket.Dispose();
            }

            if (CoreApplication.Properties.TryGetValue("listener", out outValue))
            {
                // Remove the listener from the list of application properties as we are about to close it.
                CoreApplication.Properties.Remove("listener");
                StreamSocketListener listener = (StreamSocketListener)outValue;
                listener.Dispose();
            }

            if (CoreApplication.Properties.ContainsKey("connected"))
            {
                CoreApplication.Properties.Remove("connected");
            }

            rootPage.NotifyUser("Socket and listener closed", NotifyType.StatusMessage);
        }
Exemple #5
0
        private async void StreamSocketListener_ConnectionReceived(StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args)
        {
            string request;

            using (var streamReader = new StreamReader(args.Socket.InputStream.AsStreamForRead()))
            {
                request = await streamReader.ReadLineAsync();
            }

            // Echo the request back as the response.
            using (Stream outputStream = args.Socket.OutputStream.AsStreamForWrite())
            {
                using (var streamWriter = new StreamWriter(outputStream))
                {
                    await streamWriter.WriteLineAsync(request);

                    await streamWriter.FlushAsync();
                }
            }

            sender.Dispose();
        }
Exemple #6
0
        public async Task MakeDiscoverableAsync(int metaDataPort, UPNPConfiguration config)
        {
            _ssdpDiscoveryListener = new DatagramSocket();
            _ssdpDiscoveryListener.MessageReceived += _socket_MessageReceived;

            _webListener = new StreamSocketListener();
            _webListener.ConnectionReceived += ProcessRequestAsync;

            _config = config;

            _metaDataPort = metaDataPort;

            try
            {
                await _webListener.BindServiceNameAsync(metaDataPort.ToString());
            }
            catch (Exception ex)
            {
                throw new Exception("Attempt to start Web Listener Failed on Port: " + metaDataPort.ToString(), ex);
            }

            try
            {
                await _ssdpDiscoveryListener.BindEndpointAsync(null, _config.UdpListnerPort.ToString());
            }
            catch (Exception ex)
            {
                throw new Exception("Attempt to SSDP Listener Failed on Port: " + _config.UdpListnerPort.ToString(), ex);
            }

            try
            {
                _ssdpDiscoveryListener.JoinMulticastGroup(new HostName("239.255.255.250"));
            }
            catch (Exception ex)
            {
                throw new Exception("Attempt to Join Multi Cast Group Failed", ex);
            }
        }
Exemple #7
0
        private async void StartServer()
        {
            try
            {
                //instantitate a listener
                var streamSocketListener = new StreamSocketListener();

                //挂接事件处理器。
                //每次连接后,就会调用事件处理器,接受请求,回复请求。不知道是不是每次发送都需要来回收发,最好的状态是建立一次连接,然后随便发送最好。
                // The ConnectionReceived event is raised when connections are received.
                streamSocketListener.ConnectionReceived += this.StreamSocketListener_ConnectionReceived;

                //开始监听。
                // Start listening for incoming TCP connections on the specified port. You can specify any port that's not currently in use.
                await streamSocketListener.BindServiceNameAsync("8080");
            }
            catch (Exception ex)
            {
                SocketErrorStatus webErrorStatus = SocketError.GetStatus(ex.GetBaseException().HResult);
                this.serverListBox.Items.Add(webErrorStatus.ToString() != "Unknown" ? webErrorStatus.ToString() : ex.Message);
            }
        }
Exemple #8
0
        private async void listener_ConnectionReceived(StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args)
        {
            await Task.Factory.StartNew
                (() =>
            {
                try
                {
                    // create network channel to accept connection request
                    IMqttNetworkChannel channel = new MqttNetworkChannel(args.Socket);
                    channel.Accept();

                    // handling channel for connected client
                    MqttClient client = new MqttClient(channel);
                    // raise client raw connection event
                    this.OnClientConnected(client);
                }
                catch (Exception)
                {
                    // TODO : check errors/exceptions on accepting connection
                }
            });
        }
Exemple #9
0
        private async void OnConnection(
            StreamSocketListener sender,
            StreamSocketListenerConnectionReceivedEventArgs args)
        {
            DataReader reader = new DataReader(args.Socket.InputStream);

            try
            {
                while (true)
                {
                    // Read first 4 bytes (length of the subsequent string).
                    uint sizeFieldCount = await reader.LoadAsync(sizeof(uint));

                    if (sizeFieldCount != sizeof(uint))
                    {
                        return;
                    }

                    // Read the string.
                    uint stringLength       = reader.ReadUInt32();
                    uint actualStringLength = await reader.LoadAsync(stringLength);

                    if (stringLength != actualStringLength)
                    {
                        return;
                    }

                    rootPage.NotifyUserFromAsyncThread("Received message: " + reader.ReadString(actualStringLength));
                }
            }
            catch (Exception exception)
            {
                // If this is an unknown status it means that the error is fatal and retry will likely fail.
                if (SocketError.GetStatus(exception.HResult) == SocketErrorStatus.Unknown)
                {
                    throw;
                }
            }
        }
Exemple #10
0
        private static async void OnConnection(StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args)
        {
            _streamSocket = args.Socket;

            _host            = _streamSocket.Information.RemoteAddress.ToString();
            ConnectionStatus = ConnectionStatus.Connected;
            DataReader reader = new DataReader(_streamSocket.InputStream);

            reader.InputStreamOptions = InputStreamOptions.Partial;
            _writer = new DataWriter(_streamSocket.OutputStream);

            try
            {
                while (true)
                {
                    //uint sizeFieldCount = await reader.LoadAsync(sizeof(uint));
                    //if (sizeFieldCount != sizeof(uint))
                    //{
                    //    return;
                    //}

                    //uint stringLength = 3; // reader.ReadUInt32();
                    //uint actualStringLength = await reader.LoadAsync(3);
                    //if (stringLength != actualStringLength)
                    //{
                    //    return;
                    //}

                    await reader.LoadAsync(20);

                    Message = reader.ReadString(reader.UnconsumedBufferLength);
                }
            }
            catch (Exception e)
            {
                ConnectionStatus = ConnectionStatus.Failed;
                //TODO:send a connection status message with error, then try to reconnect
            }
        }
Exemple #11
0
 public void StopServer()
 {
     try
     {
         Task.Run(async() =>
         {
             if (_streamSocketListener != null)
             {
                 await _streamSocketListener.CancelIOAsync();
                 _streamSocketListener.Dispose();
             }
             _streamSocketListener = null;
         });
     }
     catch
     {
     }
     finally
     {
         _streamSocketListener = null;
     }
 }
Exemple #12
0
        private async void SocketListener_ConnectionReceived(StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args)
        {
            if (sender != _socketListener)
            {
                return;
            }

            StreamSocket socket = args.Socket;

            _log.Debug("Incoming connection to {0}:{1} from {2}...", socket.Information.LocalAddress.DisplayName, socket.Information.LocalPort, socket.Information.RemoteAddress.DisplayName);

            HttpRequest request = await HttpRequest.GetHttpRequest(args.Socket);

            if (request == null)
            {
                return;
            }

            _log.Info("Received request from {0}: {1}", socket.Information.RemoteAddress.DisplayName, request.Uri.PathAndQuery);

            RequestReceived.Raise(this, new HttpRequestEventArgs(request));
        }
Exemple #13
0
        public async Task mainAsync()
        {
            /// 接続
            //Connecting ...
            state = "Listening";
            try
            {
                rfcommProvider = await RfcommServiceProvider.CreateAsync(RfcommServiceId.FromUuid(Constants.RfcommChatServiceUuid));
            }
            // Catch exception HRESULT_FROM_WIN32(ERROR_DEVICE_NOT_AVAILABLE).
            catch (Exception ex) when((uint)ex.HResult == 0x800710DF)
            {
                state = "None";
                return;
            }


            // Create a listener for this service and start listening
            socketListener = new StreamSocketListener();
            socketListener.ConnectionReceived += OnConnectionReceived;
            var rfcomm = rfcommProvider.ServiceId.AsString();

            await socketListener.BindServiceNameAsync(rfcommProvider.ServiceId.AsString(), SocketProtectionLevel.BluetoothEncryptionAllowNullAuthentication);

            // Set the SDP attributes and start Bluetooth advertising
            InitializeServiceSdpAttributes(rfcommProvider);

            try
            {
                rfcommProvider.StartAdvertising(socketListener, true);
            }
            catch (Exception e)
            {
                // If you aren't able to get a reference to an RfcommServiceProvider, tell the user why.  Usually throws an exception if user changed their privacy settings to prevent Sync w/ Devices.
                state = "None";
                return;
            }
            //Listening for incoming connections
        }
Exemple #14
0
        private async void StreamSocketListener_ConnectionReceived(StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args)
        {
            StreamReader streamReader = new StreamReader(args.Socket.InputStream.AsStreamForRead());
            string       handshake;

            handshake = await streamReader.ReadLineAsync();

            if (handshake.Equals("Android Input Device"))
            {
                using (Stream outputStream = args.Socket.OutputStream.AsStreamForWrite()) {
                    using (var streamWriter = new StreamWriter(outputStream)) {
                        await streamWriter.WriteLineAsync("Android Input Driver");

                        await streamWriter.FlushAsync();
                    }
                }
            }
            else
            {
                sender.Dispose();
                await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => connectButton.IsEnabled = true);

                return;
            }
            for (; ;)
            {
                string request;
                request = await streamReader.ReadLineAsync();

                if (request == null)
                {
                    await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => connectButton.IsEnabled = true);

                    sender.Dispose();
                    return;
                }
                InjectInput(request);
            }
        }
Exemple #15
0
        public async Task <bool> Start()
        {
            try
            {
                listener = new StreamSocketListener();
                listener.Control.QualityOfService = SocketQualityOfService.Normal;
                listener.ConnectionReceived      += ConnectionReceived;

                clients = new ConcurrentDictionary <Guid, ClientHandler>();

                await listener.BindServiceNameAsync(ServiceName);

                Startup?.Invoke(this, EventArgs.Empty);
            }
            catch
            {
                Stop();
                return(false);
            }

            return(true);
        }
Exemple #16
0
        //Init() erstellt einen Socket. Ein Socket ist eine Verbindung zwischen IP-Adresse und Port. Also eine eindeutige Verbindungsinformation
        //In diesem Fall habe ich mich für einen Asynchronen Socket entschieden. Dieser wird nur einmalig Initialisiert und nie wieder angefasst.
        async public Task Init(EventManager link)
        {
            EventManager = link;
            EventManager.CreateEvent(eventType.DebugMessage, "Listener wird vorbereitet...");
            try
            {
                socketListener = new StreamSocketListener();

                //Das hier ist der Trick der Asynchronen Programmierung. Ich habe einen Socket erstellt und mittels += Operator ein Event an eine Methode gekoppelt.
                //Jedes Mal wenn das Event "ConnectionReceived" auftritt wird automatisch die Methode ConnectionReceivedHandlerAsync aufgerufen.
                //Wenn nie eine Nachricht ankommen würde würde auch im Code nie etwas passieren. Es wird auf ein Event gewartete anstatt die ganze Zeit aktiv abzufragen ob
                //eine Verbindung da ist. Das spart Strom und CPU Laufzeit. Sieht dafür verwirrender für uns aus.
                socketListener.ConnectionReceived += ConnectionReceivedHandlerAsync;
                //KeepAlive = true bedeutet dass der Listener nie ausgehen soll. Stürtzt er ab startet er automatisch neu. Wir müssen uns um nix kümmern.
                socketListener.Control.KeepAlive = true;
                await socketListener.BindServiceNameAsync("9000");
            }
            catch (Exception e)
            {
                EventManager.CreateEvent(eventType.Error, e.Message);
            }
        }
        /// <summary>
        ///     Binds the <code>TcpSocketListener</code> to the specified port on all endpoints and listens for TCP connections.
        /// </summary>
        /// <param name="port">The port to listen on. If '0', selection is delegated to the operating system.</param>
        /// <param name="listenOn">The <code>CommsInterface</code> to listen on. If unspecified, all interfaces will be bound.</param>
        /// <returns></returns>
        public Task StartListeningAsync(int port, ICommsInterface listenOn = null)
        {
            if (listenOn != null && !listenOn.IsUsable)
            {
                throw new InvalidOperationException("Cannot listen on an unusable interface. Check the IsUsable property before attemping to bind.");
            }

            _listenCanceller             = new CancellationTokenSource();
            _backingStreamSocketListener = new StreamSocketListener();

            _backingStreamSocketListener.ConnectionReceived += (sender, args) =>
            {
                var nativeSocket  = args.Socket;
                var wrappedSocket = new TcpSocketClient(nativeSocket, _bufferSize);

                var eventArgs = new TcpSocketListenerConnectEventArgs(wrappedSocket);
                if (ConnectionReceived != null)
                {
                    ConnectionReceived(this, eventArgs);
                }
            };

            var sn = port == 0 ? "" : port.ToString();

#if !WP80
            if (listenOn != null)
            {
                var adapter = ((CommsInterface)listenOn).NativeNetworkAdapter;

                return(_backingStreamSocketListener
                       .BindServiceNameAsync(sn, SocketProtectionLevel.PlainSocket, adapter)
                       .AsTask());
            }
            else
#endif
            return(_backingStreamSocketListener
                   .BindServiceNameAsync(sn)
                   .AsTask());
        }
Exemple #18
0
        private async void Listener_ConnectionReceived(StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args)
        {
            Debug.WriteLine("Got connection");

            uint bufferSize = 1024 * 8;

            byte[] buffer    = new byte[bufferSize];
            uint   realCount = 0;

            using (MemoryStream ms = new MemoryStream())
                using (var dr = new DataReader(args.Socket.InputStream))
                {
                    dr.InputStreamOptions = InputStreamOptions.Partial;

                    while ((realCount = await dr.LoadAsync(bufferSize)) > 0)
                    {
                        dr.ReadBytes(buffer);
                        await ms.WriteAsync(buffer, 0, (int)realCount);
                    }
                    var str = System.Text.Encoding.UTF8.GetString(ms.ToArray());
                    Debug.WriteLine($"data:{str}");
                    OnReceived.Invoke(System.Text.Encoding.UTF8.GetString(ms.ToArray()));
                }

            using (var dw = new DataWriter(args.Socket.OutputStream))
            {
                dw.WriteString(@"HTTP/1.1 200 OK
Cache-Control: private
Connection: Keep-Alive
Content-Length: 0
Content-Type: text/html; charset=UTF-8
Server: kumblr

");
                await dw.StoreAsync();

                dw.DetachStream();
            }
        }
Exemple #19
0
 public void Close()
 {
     if (writer != null)
     {
         writer.DetachStream();
         writer.Dispose();
         rootPage.NotifyUser("DataWriter closed.");
     }
     if (socket != null)
     {
         socket.Dispose();
         rootPage.NotifyUser("Socket closed.");
     }
     if (listener != null)
     {
         listener.Dispose();
         rootPage.NotifyUser("No longer listening.");
     }
     writer   = null;
     listener = null;
     socket   = null;
 }
Exemple #20
0
    // Stream outputStream = null;
#endif


#if !UNITY_EDITOR
    async void Start()
    {
        sensorDisplay = GetComponent <SensorDisplay>();
        Debug.Log("Waiting for a connection...");
        //System.Diagnostics.Debug.Write("Waiting for a connection...");
        try {
            socketListener = new StreamSocketListener();
            socketListener.ConnectionReceived += Socket_ConnectionReceived;
            await socketListener.BindServiceNameAsync(port);
        } catch (Exception e) {
            Debug.Log(e.ToString());
            return;
        }

        for (int i = 0; i < TCPPackageConstants.TOTAL_NUM_TF; i++)
        {
            tfDataArr[i] = new tfData();
        }
        Debug.Log("TF array initialized");

        Debug.Log("exit start");
    }
Exemple #21
0
        private void ListenerOnConnectionReceived(StreamSocketListener sender,
                                                  StreamSocketListenerConnectionReceivedEventArgs args)
        {
            try
            {
                if (args.Socket == null)
                {
                    return;
                }
                var peerSocket = args.Socket;
                var uri        = new Uri("tcp://" + peerSocket.Information.RemoteHostName.RawName + ':' +
                                         peerSocket.Information.RemoteServiceName);
                var         peer       = new Peer("", uri, EncryptionTypes.All);
                IConnection connection = new TCPConnection(peerSocket, true);


                RaiseConnectionReceived(peer, connection, null);
            }
            catch
            {
            }
        }
Exemple #22
0
        protected override async void ConnectAsync(string ip, ushort port)
        {
            socket = new StreamSocketListener();
            socket.Control.QualityOfService = SocketQualityOfService.Normal;
            socket.ConnectionReceived      += ConnectionReceived;

            // Binding listener to a port
            try
            {
                await socket.BindServiceNameAsync(port.ToString());

                Connected = true;

                OnConnected();

                Me = new NetworkingPlayer(Uniqueidentifier, ip, socket, "SERVER");
            }
            catch (Exception e)
            {
                ErrorDisconnect(e.Message);
            }
        }
Exemple #23
0
        public virtual void StartServer()
        {
            listener = new StreamSocketListener();
            listener.Control.KeepAlive = true;
            listener.Control.NoDelay   = true;

            listener.ConnectionReceived += async(s, e) => {
                try
                {
                    await ProcessRequestAsync(e.Socket);
                }
                catch (Exception exc)
                {
                    ;
                }
            };

            Task.Run(async() => {
                await listener.BindServiceNameAsync(port.ToString(), SocketProtectionLevel.PlainSocket);
            },
                     tokenSource.Token);
        }
Exemple #24
0
        private async void ConnectionReceived(StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args)
        {
            // sự kiện được kích hoạt trên một threat khác, không có quyền truy cập trực tiếp đến biến cục bộ của thread hiện tại.
            // nên thay vì gán như thông thường ta cần dùng dispatcher để gán bằng thread

            //this.textDebug.Text += "Server Received\n"; // => crash

            await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal,
                                                                          async() =>
            {
                textDebug.Text += "Server received message from: " + args.Socket.Information.RemoteAddress + "\n";

                if (_streamsocket == null)
                {
                    _streamsocket = new StreamSocket();
                    await _streamsocket.ConnectAsync(args.Socket.Information.RemoteAddress, _port.ToString());
                }
                var msg              = await this.readMessage(args.Socket.InputStream);
                this.textDebug.Text += "Receive from " + args.Socket.Information.RemoteAddress + ": " + msg + "\n";
            }
                                                                          );
        }
Exemple #25
0
        private void OnSocketConnectionReceived(StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args)
        {
            Windows.Foundation.IAsyncAction task = Dispatcher.RunAsync(CoreDispatcherPriority.Normal, async() =>
            {
                //rootPage.NotifyUser("Connecting to remote side on L4 layer...", NotifyType.StatusMessage);
                StreamSocket serverSocket = args.Socket;

                SocketReaderWriter socketRW = new SocketReaderWriter(serverSocket, this);
                // The first message sent is the name of the connection.
                string message = await socketRW.ReadMessageAsync();

                // Find the pending connection and add it to the list of active connections.
                if (_pendingConnections.TryRemove(sender, out WiFiDirectDevice wfdDevice))
                {
                    ConnectedDevices.Add(new ConnectedDevice(message, wfdDevice, socketRW));
                }

                while (message != null)
                {
                    message = await socketRW.ReadMessageAsync();
                }
            });
Exemple #26
0
        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="serverPort">Port to start server on</param>
        internal HttpInterfaceManager(int serverPort, IPlaybackManager playbackManager, IPlaylistManager playlistManager, IDevicePowerManager powerManager)
        {
            this.playbackManager = playbackManager;
            this.playlistManager = playlistManager;
            this.powerManager    = powerManager;

            helper   = new WebHelper();
            listener = new StreamSocketListener();
            port     = serverPort;
            listener.ConnectionReceived += (s, e) =>
            {
                try
                {
                    // Process incoming request
                    processRequestAsync(e.Socket);
                }
                catch (Exception ex)
                {
                    Debug.WriteLine("Exception in StreamSocketListener.ConnectionReceived(): " + ex.Message);
                }
            };
        }
Exemple #27
0
    private async void ListenerConnectionReceived(StreamSocketListener sender,
                                                  StreamSocketListenerConnectionReceivedEventArgs args)
    {
        Debug.Log("Connection received");

        try
        {
            using (var reader = new DataReader(args.Socket.InputStream))
            {
                reader.InputStreamOptions = InputStreamOptions.Partial;

                await reader.LoadAsync(sizeof(uint));

                uint dsize = reader.ReadUInt32();

                await reader.LoadAsync(dsize);

                uint      len  = dsize / sizeof(uint) / 3;
                Vector3[] path = new Vector3[len];

                for (int i = 0; i < len; i++)
                {
                    path[i].x = reader.ReadSingle();
                    path[i].y = reader.ReadSingle();
                    path[i].z = reader.ReadSingle();
                }

                queue_.Enqueue(path);
                Debug.Log("received: " + dsize + ", " + len);
                Debug.Log(path[0].ToString());
            }
        }
        catch (Exception e)
        {
            Debug.Log("[ERROR] Disconnected" + e);
        }

        // Debug.Log("Sender disposed");
    }
        private async void OnLoaded()
        {
            this.Command.Focus(FocusState.Keyboard);

            this.ConsoleText.SizeChanged += (o, e) => this.ServerConsole.ChangeView(0, double.MaxValue, null);
            this.GameText.SizeChanged    += (o, e) => this.GameConsole.ChangeView(0, double.MaxValue, null);

            try
            {
                this.serverSocket = new StreamSocketListener();
                this.serverSocket.ConnectionReceived += this.ServerSocketConnectionReceived;
                await this.serverSocket.BindServiceNameAsync(ServiceName);

                this.SafeAddText(s => ConsoleText.Text += s, "Server is listening...");
            }
            catch (Exception ex)
            {
                this.ConsoleText.Text = GetErrorText(ex);
                throw;
            }

            try
            {
                var hostName = new HostName("localhost");
                this.clientSocket = new StreamSocket();
                await this.clientSocket.ConnectAsync(hostName, ServiceName);

                clientWriter = new DataWriter(this.clientSocket.OutputStream);
                clientReader = new DataReader(this.clientSocket.InputStream);
                this.SafeAddText(s => GameText.Text += s, "Connected to server!");
                var longRunningTask = Task.Factory.StartNew(ClientListener, null, TaskCreationOptions.LongRunning);
                await SendString(clientWriter, "look");
            }
            catch (Exception ex)
            {
                this.GameText.Text = GetErrorText(ex);
                throw;
            }
        }
Exemple #29
0
        private async void ProcessRequest(StreamSocketListener streamSocktetListener, StreamSocketListenerConnectionReceivedEventArgs eventArgs)
        {
            try
            {
                var socket = eventArgs.Socket;

                //Read request
                var request = await ReadRequest(socket);

                //Write Response
                await WriteResponse(request, socket);

                socket.InputStream.Dispose();
                socket.OutputStream.Dispose();
                socket.Dispose();
            }
            catch (Exception ex)
            {
                Debug.WriteLine("Something went wrong while processing the request"); //TODO: change this
                Debug.WriteLine(ex.Message);
            }
        }
Exemple #30
0
        public WebServer(int serverPort)
        {
            listener = new StreamSocketListener();
            port     = serverPort;

            mimeTypeMap.Add(".htm", "text/html");
            mimeTypeMap.Add(".html", "text/html");
            mimeTypeMap.Add(".asp", "text/html");
            mimeTypeMap.Add(".css", "text/css");
            mimeTypeMap.Add(".js", "text/javascript");
            mimeTypeMap.Add(".bmp", "image/bmp");
            mimeTypeMap.Add(".jpg", "image/jpeg");
            mimeTypeMap.Add(".png", "image/png");

            //Add event handler for HTTP connections
            listener.ConnectionReceived += (s, e) => ProcessRequestAsync(e.Socket);

            System.Diagnostics.Debug.WriteLine("Sprinkler Web server starting...");
            System.Diagnostics.Debug.WriteLine("Current dir: " + Directory.GetCurrentDirectory());

            sMyWebServerRoot = String.Format(@"{0}\web", Directory.GetCurrentDirectory());
        }