예제 #1
0
        /// <summary>
        /// Creates a TCP socket and binds to the CommunicationPort.
        /// Use the default JsonSerializer if null is passed into the serializer parameter.
        /// Returns false if you are already listening.
        /// </summary>
        public async Task <bool> StartListeningAsync()
        {
            if (_localSocket == null)
            {
                _localSocket = new StreamSocketListener();
                _localSocket.ConnectionReceived += LocalSocketConnectionReceived;
                await _localSocket.BindServiceNameAsync(CommunicationPort);

                return(true);
            }

            return(false);
        }
예제 #2
0
 public async Task StartAsync()
 {
     try
     {
         await Listener.BindServiceNameAsync(Port.ToString());
     }
     catch (Exception)
     {
         Port++;
         await StartAsync().ConfigureAwait(false);
     }
     RegisterDeviceAsync(IP, Port, Hostname);
 }
예제 #3
0
        public async Task Start()
        {
            DebugHelper.LogInformation($"StreamSocket Server starting on port {SharedConstants.DEVICE_API_PORT}");

            await WaitForAPInterface();

            StreamSocketListener listener = new StreamSocketListener();

            listener.ConnectionReceived += ConnectionReceived;
            await listener.BindServiceNameAsync(SharedConstants.DEVICE_API_PORT.ToString());

            DebugHelper.LogInformation($"Listening for StreamSocket connection on {SharedConstants.DEVICE_API_PORT}");
        }
 public void Start()
 {
     Lock(this)                     //prevent any other code interupting
     {
         if (!Running)              //prevent multiple starts
         {
             listener = new StreamSocketListener();
             listener.BindServiceNameAsync("8080");
             listener.ConnectionReceived += listener_ConnectionReceived;
             Running = true;
         }
     }
 }
예제 #5
0
        /// <summary>
        /// Configures the network transmitter as the source.
        /// </summary>
        public void ConfigureAsServer()
        {
            Task t = new Task(() =>
            {
                Debug.Log("Starting import export server");
                networkListener = new StreamSocketListener();
                networkListener.ConnectionReceived += NetworkListener_ConnectionReceived;
                networkListener.BindServiceNameAsync(SendConnectionPort.ToString()).GetResults();
            }
                              );

            t.Start();
        }
예제 #6
0
        } // End of Constructor

        public async Task StartListener(Action <string> action)
        {
            _action = action;

            //Create a StreamSocketListener to start listening for TCP connections.
            StreamSocketListener socketListener = new StreamSocketListener();

            //Hook up an event handler to call when connections are received.
            socketListener.ConnectionReceived += SocketListener_ConnectionReceived;

            //Start listening for incoming TCP connections on the specified port. You can specify any port that' s not currently in use.
            await socketListener.BindServiceNameAsync(_portNumber);
        } // End of StartListener
        /// <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());
        }
예제 #8
0
        public void Start(MqttServerOptions options)
        {
            if (_socket != null)
            {
                throw new InvalidOperationException("Server is already started.");
            }

            _cancellationTokenSource = new CancellationTokenSource();

            _socket = new StreamSocketListener();
            _socket.BindServiceNameAsync(options.Port.ToString()).AsTask().Wait();
            _socket.ConnectionReceived += ConnectionReceived;
        }
예제 #9
0
        /// <summary>
        /// Server listens to specified port and accepts connection from client
        /// </summary>
        public async void StartListen()
        {
            // var ip = (networkInterface != null)
            //     ? GetInterfaceIpAddress()
            //     : IPAddress.Any;

            tcpServer = new StreamSocketListener();
            tcpServer.ConnectionReceived += TcpServer_ConnectionReceived;
            await tcpServer.BindServiceNameAsync(portNumber.ToString(), SocketProtectionLevel.PlainSocket);


            isRunning = true;
        }
예제 #10
0
        protected override async Task StartCoreAsync()
        {
            var serviceId = RfcommServiceId.FromUuid(_serviceUuid);

            _serviceProvider = await RfcommServiceProvider.CreateAsync(serviceId);

            _listener.ConnectionReceived += OnConnectionReceived;
            await _listener.BindServiceNameAsync(serviceId.AsString(),
                                                 SocketProtectionLevel.BluetoothEncryptionAllowNullAuthentication);

            InitializeServiceSdpAttributes(_serviceProvider);
            _serviceProvider.StartAdvertising(_listener, true);
        }
예제 #11
0
        public async Task StartListener()
        {
            try
            {
                _streamSocketListener = new StreamSocketListener();
                _streamSocketListener.ConnectionReceived += StreamSocketListener_ConnectionReceived;

                await _streamSocketListener.BindServiceNameAsync("4537");
            }
            catch (Exception ex)
            {
                SocketErrorStatus webErrorStatus = SocketError.GetStatus(ex.GetBaseException().HResult);
            }
        }
예제 #12
0
    private async void StartServer()
    {
        try
        {  // Start listening for incoming TCP connections on the specified port. You can specify any port that's not currently in use.
            await streamSocketListener.BindServiceNameAsync(port.ToString());

            Debug.Log("server is listening...");
        }
        catch (System.Exception ex)
        {
            Windows.Networking.Sockets.SocketErrorStatus webErrorStatus = Windows.Networking.Sockets.SocketError.GetStatus(ex.GetBaseException().HResult);
            Debug.Log(webErrorStatus.ToString() != "Unknown" ? webErrorStatus.ToString() : ex.Message);
        }
    }
예제 #13
0
        /// <summary>
        /// Initialize the REST server and open a socket for listening on port 80.
        /// </summary>
        /// <param name="wwwroot">storage folder from which files are served</param>
        public async void Initialise(StorageFolder wwwroot)
        {
            listener     = new StreamSocketListener();
            this.wwwroot = wwwroot;

            // listen on port 80, this is the standard HTTP port (use a different port if you have a service already running on 80)
            await listener.BindServiceNameAsync("80", SocketProtectionLevel.PlainSocket);

            listener.ConnectionReceived += (sender, args) =>
            {
                // call the handle request function when a request comes in
                HandleRequest(sender, args);
            };
        }
예제 #14
0
        private async void StartListing_Click(object sender, RoutedEventArgs e)
        {
            // Listener für Annahme von TCP-Verbindungsanfragen erzeugen
            _listener = new StreamSocketListener();

            // Eventhandler registrieren, um Verbindungsanfragen zu bearbeiten
            _listener.ConnectionReceived += Listener_ConnectionReceived;

            // Lauschen und warten auf Verbindungen starten
            Status.Text = "Starte Listener...";
            await _listener.BindServiceNameAsync(Port);

            Status.Text = "Listener bereit.";
        }
예제 #15
0
    private async void Launch()
    {
        Debug.Log("Listener started");
        try
        {
            await listener_.BindServiceNameAsync(port_);
        }
        catch (Exception e)
        {
            Debug.Log("Error: " + e.Message);
        }

        Debug.Log("Listening");
    }
예제 #16
0
        public async void Start()
        {
            var listener = new StreamSocketListener();

            await listener.BindServiceNameAsync("8085");

            listener.ConnectionReceived += async(sender, args) =>
            {
                var request = new StringBuilder();

                using (var input = args.Socket.InputStream)
                {
                    var     data     = new byte[BufferSize];
                    IBuffer buffer   = data.AsBuffer();
                    var     dataRead = BufferSize;

                    while (dataRead == BufferSize)
                    {
                        await input.ReadAsync(
                            buffer, BufferSize, InputStreamOptions.Partial);

                        request.Append(Encoding.UTF8.GetString(
                                           data, 0, data.Length));
                        dataRead = buffer.Length;
                    }
                }

                string pinStatus = GetPinStatus();

                using (var output = args.Socket.OutputStream)
                {
                    using (var response = output.AsStreamForWrite())
                    {
                        var html = Encoding.UTF8.GetBytes(
                            $"<html><head><title>Background Message</title></head><body>Hello from the background process!<br/>{pinStatus}</body></html>");
                        using (var bodyStream = new MemoryStream(html))
                        {
                            var header      = $"HTTP/1.1 200 OK\r\nContent-Length: {bodyStream.Length}\r\nConnection: close\r\n\r\n";
                            var headerArray = Encoding.UTF8.GetBytes(header);
                            await response.WriteAsync(headerArray,
                                                      0, headerArray.Length);

                            await bodyStream.CopyToAsync(response);

                            await response.FlushAsync();
                        }
                    }
                }
            };
        }
예제 #17
0
        /* public MyWebserver(AppServiceConnection connection)
         * {
         *   _connection = connection;
         *   _connection.RequestReceived += ConnectionRequestReceived;
         * }
         *
         * private void ConnectionRequestReceived(AppServiceConnection sender, AppServiceRequestReceivedEventArgs args)
         * {
         *   _name = (string)args.Request.Message.First().Value;
         * }
         */
        public async void Start()
        {
            var listener = new StreamSocketListener();

            await listener.BindServiceNameAsync("8081");

            listener.ConnectionReceived += async(sender, args) =>
            {
                StringBuilder request = new StringBuilder();

                using (IInputStream input = args.Socket.InputStream)
                {
                    byte[]  data     = new byte[BufferSize];
                    IBuffer buffer   = data.AsBuffer();
                    uint    dataRead = BufferSize;

                    while (dataRead == BufferSize)
                    {
                        await input.ReadAsync(
                            buffer, BufferSize, InputStreamOptions.Partial);

                        request.Append(Encoding.UTF8.GetString(
                                           data, 0, data.Length));
                        dataRead = buffer.Length;
                    }
                }

                string query = GetQuery(request);

                using (IOutputStream output = args.Socket.OutputStream)
                {
                    using (Stream response = output.AsStreamForWrite())
                    {
                        byte[]       html       = Encoding.GetEncoding("iso-8859-1").GetBytes($"<html><head><title>Background Message</title></head><body>Hello from the background process!<br/>{query}</body></html>");
                        MemoryStream bodyStream = new MemoryStream(html);

                        string header = "HTTP/1.1 200 OK\r\n" +
                                        $"Content-Length: {bodyStream.Length}\r\n" +
                                        "Connection: close\r\n\r\n";                            //var headerArray = Encoding.UTF8.GetBytes(header);
                        byte[] headerArray = Encoding.GetEncoding("iso-8859-1").GetBytes(header);
                        await response.WriteAsync(headerArray,
                                                  0, headerArray.Length);

                        await bodyStream.CopyToAsync(response);

                        await response.FlushAsync();
                    }
                }
            };
        }
예제 #18
0
        /// <summary>
        ///  Starts the service listener if it is in a stopped state.
        /// </summary>
        /// <param name="servicePort">The port used to listen on.</param>
        public bool Start(string servicePort)
        {
            try
            {
                _listener = new StreamSocketListener();

#pragma warning disable CS4014
                if (InterfaceAdapter == null)
                {
                    _listener.BindServiceNameAsync(servicePort);
                }
                else
                {
                    _listener.BindServiceNameAsync(servicePort, SocketProtectionLevel.PlainSocket, InterfaceAdapter);
                }
#pragma warning restore CS4014

                _listener.ConnectionReceived += OnClientConnected;
                _logger.Info("Websocket listener Started on {0}", _listener.Information.LocalPort.ToString());

                //_logger.Info("Listener Started on {0}", ActivePort.ToString());
            }
            catch (Exception ex)
            {
                // If this is an unknown status it means that the error is fatal and retry will likely fail.
                if (SocketError.GetStatus(ex.HResult) == SocketErrorStatus.Unknown)
                {
                    IsActive = false;
                    ListenerError(_listener, ex);
                    return(false);
                }
                _logger.Error("Start listening failed with error: {0}" + ex.Message, ex);
            }

            IsActive = true;
            return(true);
        }
예제 #19
0
        public async Task <bool> CreateListener()
        {
            bool alright = false;

            //Create a StreamSocketListener to start listening for TCP connections.
            try
            {
                try
                {
                    string myIP = Networking.GetLocalIp();
                    mp.myIP(myIP);


                    await Networking.sendIP(myIP);

                    mp.status("Sent my IP.", Colors.LightGray);
                    mp.print("Sent my ip " + myIP + " on web server for client to read");
                    alright = true;
                }
                catch (Exception ex)
                {
                    mp.print("Error while sending my IP: " + ex.Message);
                    mp.status("Couldn't send my IP", Colors.DarkRed);
                }
                try
                {
                    StreamSocketListener socketListener = new
                                                          StreamSocketListener();
                    await socketListener.BindServiceNameAsync(mp.Port);

                    socketListener.ConnectionReceived += SocketListener_ConnectionReceived;
                    if (Connected)
                    {
                        Connected = false;
                    }
                    else
                    {
                        Connected = true;
                    }
                }
                catch (Exception ex) { mp.print("Error while creaitng listener: " + ex.Message); alright = false; }
            }
            catch (Exception ex)
            {
                mp.print(ex.Message);
                alright = false;
            }
            return(alright);
        }
예제 #20
0
 Task listenProcess() => Task.Run(async() =>
 {
     var p = await RfcommServiceProvider.CreateAsync(BluetoothUtils.RfcommConnectionService);
     using (var l = new StreamSocketListener())
     {
         l.ConnectionReceived += (sender, e) => new ErebusLink(new SplitStream(e.Socket.InputStream.AsStreamForRead(), e.Socket.OutputStream.AsStreamForWrite()), ei, true);
         await l.BindServiceNameAsync(BluetoothUtils.RfcommConnectionService.AsString(), SocketProtectionLevel.BluetoothEncryptionWithAuthentication);
         p.StartAdvertising(l);
         while (process)
         {
             await Task.Delay(10);
         }
         p.StopAdvertising();
     }
 });
        public async void StartServer()
        {
            // Initialize the provider for the hosted RFCOMM service.
            provider = await RfcommServiceProvider.CreateAsync(RfcommServiceId.ObexObjectPush);

            // Create a listener for this service and start listening.
            socketListener = new StreamSocketListener();
            socketListener.ConnectionReceived += OnConnectionReceived;
            await socketListener.BindServiceNameAsync(provider.ServiceId.AsString(), SocketProtectionLevel.BluetoothEncryptionAllowNullAuthentication);

            // Set the SDP attributes and start advertising.
            InitializeServiceSdpAttributes(provider);
            provider.StartAdvertising(socketListener);
            isAdvertising = true;
        }
예제 #22
0
        public async Task Start()
        {
            DebugHelper.LogInformation($"WebServer starting on port {SharedConstants.DEVICE_API_PORT}");

            var network = await WaitForAPInterface();

            var listener = new StreamSocketListener();

            listener.Control.QualityOfService = SocketQualityOfService.LowLatency;
            await listener.BindServiceNameAsync(SharedConstants.DEVICE_API_PORT.ToString());

            listener.ConnectionReceived += ConnectionReceived;

            DebugHelper.LogInformation($"Listening for WebServer connection on {SharedConstants.DEVICE_API_PORT}");
        }
예제 #23
0
        public void ConnectServer(int port)
        {
#if WINDOWS_UWP
            Task.Run(async() =>
            {
                socketlistener = new StreamSocketListener();
                socketlistener.ConnectionReceived += ConnectionReceived;
                await socketlistener.BindServiceNameAsync(port.ToString());
            });
#else
            tcpListener = new TcpListener(IPAddress.Any, port);
            tcpListener.Start();
            tcpListener.BeginAcceptTcpClient(AcceptTcpClient, tcpListener);
#endif
        }
예제 #24
0
        public static async void StartListener()
        {
            try
            {
                listener = new StreamSocketListener();
                listener.ConnectionReceived += OnConnection;
                await listener.BindServiceNameAsync(hostPort);

                Debug.WriteLine("Listening on {0}", hostPort);
            }
            catch (Exception e)
            {
                Debug.WriteLine("StartListener() - Unable to bind listener. " + e.Message);
            }
        }
예제 #25
0
 private async void Listener_Start()
 {
     tm.text = "Started";
     Debug.Log("Listener started");
     try
     {
         await listener.BindServiceNameAsync(port);
     }
     catch (Exception e)
     {
         tm.text = "Error: " + e.Message;
         Debug.Log("Error: " + e.Message);
     }
     //tm.text = "Listening~";
 }
예제 #26
0
 public async Task start(string servicename)
 {
     try
     {
         await listener.BindServiceNameAsync(servicename);
     }
     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;
         }
     }
 }
예제 #27
0
        public async Task InitializeAsync()
        {
            // Initialize the provider for the hosted RFCOMM service
            _provider = await RfcommServiceProvider.CreateAsync(RfcommServiceId.FromUuid(Constants.SERVICE_UUID));

            // Create a listener for this service and start listening
            _listener = new StreamSocketListener();
            _listener.ConnectionReceived += OnConnectionReceivedAsync;

            await _listener.BindServiceNameAsync(_provider.ServiceId.AsString(), SocketProtectionLevel.BluetoothEncryptionAllowNullAuthentication);

            // Set the SDP attributes and start advertising
            InitializeServiceSdpAttributes(_provider);
            _provider.StartAdvertising(_listener, true);
        }
예제 #28
0
        public async void Init()
        {
            listener = new StreamSocketListener();
            listener.ConnectionReceived += Connected;
            CoreApplication.Properties.Add("listener", listener);

            try
            {
                await listener.BindServiceNameAsync("moviePlayer");
            }
            catch (Exception e)
            {
                throw e;
            }
        }
예제 #29
0
        /// <summary>
        /// Starts server.
        /// </summary>
        /// <param name="port">Port</param>
        public async void Start(int port)
        {
            try
            {
                //Create a StreamSocketListener to start listening for TCP connections.
                StreamSocketListener socketListener = new StreamSocketListener();

                //Hook up an event handler to call when connections are received.
                socketListener.ConnectionReceived += SocketListener_ConnectionReceived;

                //Start listening for incoming TCP connections on the specified port. You can specify any port that's not currently in use.
                await socketListener.BindServiceNameAsync(port.ToString());
            }
            catch { }
        }
예제 #30
0
        public async void InitializeReceiver()
        {
            // Initialize the provider for the hosted RFCOMM service // RfcommServiceId FromUuid(Guid uuid);
            _provider = await RfcommServiceProvider.CreateAsync(RfcommServiceId.FromUuid(btUuid));

            // Create a listener for this service and start listening
            _listener = new StreamSocketListener();
            _listener.ConnectionReceived += Listener_ConnectionReceived;

            await _listener.BindServiceNameAsync(_provider.ServiceId.AsString(), SocketProtectionLevel.BluetoothEncryptionAllowNullAuthentication);

            // Set the SDP attributes and start advertising
            InitializeServiceSdpAttributes(_provider);
            _provider.StartAdvertising(_listener);
        }