예제 #1
0
        private async void OnConnectionReceived(StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args)
        {
            // Don't need the listener anymore
            socketListener.Dispose();
            socketListener = null;

            try {
                socket = args.Socket;
            } catch (Exception e) {
                System.Diagnostics.Debug.WriteLine("Error: Could not get socket");
                Disconnect();
                return;
            }

            bluetoothDevice = await BluetoothDevice.FromHostNameAsync(socket.Information.RemoteHostName);

            writer = new DataWriter(socket.OutputStream);
            reader = new DataReader(socket.InputStream);

            System.Diagnostics.Debug.WriteLine("Connected to Client");
            isConnected = true;
            OnConnected();

            mainLoop();
        }
        private async void Disconnect()
        {
            if (_rfcommProvider != null)
            {
                _rfcommProvider.StopAdvertising();
                _rfcommProvider = null;
            }

            if (_socketListener != null)
            {
                _socketListener.Dispose();
                _socketListener = null;
            }

            if (_writer != null)
            {
                _writer.DetachStream();
                _writer = null;
            }

            if (_socket != null)
            {
                _socket.Dispose();
                _socket = null;
            }
            await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
            {
                ListenButton.IsEnabled     = true;
                DisconnectButton.IsEnabled = false;
                ConversationListBox.Items.Clear();
            });
        }
예제 #3
0
        private async void Listener_ConnectionReceived(StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args)
        {
            try
            {
                //获取tcp输入流,当tcp连接结束时,流也随之结束
                String TcpData = "";
                using (StreamReader streamReader = new StreamReader(args.Socket.InputStream.AsStreamForRead()))
                {
                    while (!streamReader.EndOfStream)
                    {
                        TcpData += streamReader.ReadLine();
                        await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () => LogTextBox.Text += TcpData + "\r\n");

                        Debug.WriteLine(TcpData);
                        SolveTcpData(TcpData);
                    }
                }

                args.Socket.Dispose();
            }
            catch (Exception ex)
            {
                listener.Dispose();
                listener = null;
                Debug.WriteLine(ex.Message);
            }
        }
예제 #4
0
        private ObservableCollection <MessageInfo> MessageList; //消息列表

        #region 开启监听
        /// <summary>
        /// 开启监听
        /// </summary>
        /// <param name="ServerPort">监听端口</param>
        private async void Listen(string ServerPort)
        {
            if (listener != null)
            {
                listener.Dispose();
                listener = null;
            }
            listener = new StreamSocketListener();

            try
            {
                ConnectionProgressRing.IsActive = true;
                OnButton.IsEnabled = false;

                await listener.BindServiceNameAsync(ServerPort);            //绑定监听端口

                listener.ConnectionReceived += listener_ConnectionReceived; //注册监听完成事件
                DBManager.NotifyMsg(MessageList);                           //输出聊天记录
                ConnectionProgressRing.IsActive = false;
                OnButton.IsEnabled  = false;
                OffButton.IsEnabled = true;
            }
            catch
            {
                ConnectionProgressRing.IsActive = false;
                Disconnection();
            }
        }
        private async void Disconnect()
        {
            if (rfcommProvider != null)
            {
                rfcommProvider.StopAdvertising();
                rfcommProvider = null;
            }

            if (socketListener != null)
            {
                socketListener.Dispose();
                socketListener = null;
            }

            if (writer != null)
            {
                writer.DetachStream();
                writer = null;
            }

            if (socket != null)
            {
                socket.Dispose();
                socket = null;
            }
            //await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
            //{
            //    ListenButton.IsEnabled = true;
            //    DisconnectButton.IsEnabled = false;
            //    ConversationListBox.Items.Clear();
            //});
        }
예제 #6
0
        private void Disconnect()
        {
            if (rfcommProvider != null)
            {
                rfcommProvider.StopAdvertising();
                rfcommProvider = null;
            }

            if (socketListener != null)
            {
                socketListener.Dispose();
                socketListener = null;
            }

            if (writer != null)
            {
                writer.DetachStream();
                writer = null;
            }

            if (socket != null)
            {
                socket.Dispose();
                socket = null;
            }
        }
예제 #7
0
        /// <summary>
        /// Starts listening to Port
        /// First initialize new instance of StreamSocketListener and hook up event
        /// </summary>
        /// <returns></returns>
        public async Task StartListening(int port)
        {
            this.port = port;

            if (streamSocketListener != null)
            {
                streamSocketListener.ConnectionReceived -= onConnectionReceived;
                streamSocketListener.Dispose();
            }

            streamSocketListener = new StreamSocketListener();
            streamSocketListener.ConnectionReceived += onConnectionReceived;

            // If necessary, tweak the listener's control options before carrying out the bind operation.
            // These options will be automatically applied to the connected StreamSockets resulting from
            // incoming connections (i.e., those passed as arguments to the ConnectionReceived event handler).
            // Refer to the StreamSocketListenerControl class' MSDN documentation for the full list of control options.
            //socketListener.Control.KeepAlive = false;
            //socketListener.Control.QualityOfService = SocketQualityOfService.LowLatency;
            //socketListener.Control.NoDelay = false;
            try
            {
                await streamSocketListener.BindEndpointAsync(null, port.ToString());
            }
            catch (Exception exception)
            {
                await StartListening(port + 1);

                if (port > 22120)
                {
                    await messagingService.ShowErrorDialogAsync(exception);
                }
            }
        }
예제 #8
0
 private void DisposeListener()
 {
     if (listener != null)
     {
         listener.Dispose();
         listener = null;
     }
 }
예제 #9
0
        /// <summary>
        /// Invoked when the socket listener accepted an incoming Bluetooth connection.
        /// </summary>
        /// <param name="sender">The socket listener that accecpted the connection.</param>
        /// <param name="args">The connection accept parameters, which contain the connected socket.</param>
        private async void OnConnectionReceived(
            StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args)
        {
            try
            {
                NotifyStatus("Client Connected");

                // Don't need the listener anymore
                socketListener.Dispose();
                socketListener = null;

                socket = args.Socket;

                writer = new DataWriter(socket.OutputStream);

                var  reader = new DataReader(socket.InputStream);
                bool remoteDisconnection = false;
                while (true)
                {
                    uint readLength = await reader.LoadAsync(sizeof(uint));

                    if (readLength < sizeof(uint))
                    {
                        remoteDisconnection = true;
                        break;
                    }
                    uint currentLength = reader.ReadUInt32();

                    readLength = await reader.LoadAsync(currentLength);

                    if (readLength < currentLength)
                    {
                        remoteDisconnection = true;
                        break;
                    }
                    string message = reader.ReadString(currentLength);

                    await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
                    {
                        ConversationListBox.Items.Add("Received: " + message);
                    });
                }

                reader.DetachStream();
                if (remoteDisconnection)
                {
                    await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
                    {
                        Disconnect();
                        NotifyStatus("Client disconnected.");
                    });
                }
            }
            catch (Exception e)
            {
                NotifyError(e);
            }
        }
        /// <summary>
        /// Invoked when the socket listener accepts an incoming Bluetooth connection.
        /// </summary>
        /// <param name="sender">The socket listener that accepted the connection.</param>
        /// <param name="args">The connection accept parameters, which contain the connected socket.</param>
        private void OnConnectionReceived(StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args)
        {
            // Don't need the listener anymore
            _socketListener.Dispose();
            _socketListener = null;

            StartReader(args.Socket);

            App.LogService.Write("Incoming Bluetooth connection received: " + args.Socket.Information.RemoteServiceName);
        }
예제 #11
0
 /// <summary>
 /// Stops the Vaser Server
 /// </summary>
 public void Stop()
 {
     ServerOnline = false;
     if (_socketListener != null)
     {
         _socketListener.Dispose();
     }
     DoStop();
     //_aTimer.Enabled = false;
 }
예제 #12
0
 internal void Close()
 {
     if (_TCPListener != null)
     {
         _TCPListener.Dispose();
     }
     if (_UDPListener != null)
     {
         _UDPListener.Dispose();
     }
 }
 private void HandleConnectionReceived(StreamSocketListener listener,
                                       StreamSocketListenerConnectionReceivedEventArgs args)
 {
     provider.StopAdvertising();
     listener.Dispose();
     DoConnect(args.Socket);
 }
예제 #14
0
        private async void Disconnect()
        {
            if (_provider != null)
            {
                _provider.StopAdvertising();
                _provider = null;
            }

            if (_listener != null)
            {
                _listener.Dispose();
                _listener = null;
            }

            if (_writer != null)
            {
                _writer.DetachStream();
                _writer = null;
            }

            if (_socket != null)
            {
                _socket.Dispose();
                _socket = null;
            }
        }
예제 #15
0
 public void Dispose()
 {
     _senseHat.ClearDisplay();
     _senseHat.UpdateDisplay();
     _senseHat.Dispose();
     listener.Dispose();
 }
예제 #16
0
 internal async Task StartListeningAsync(string port)
 {
     if (_listener == null && !Connected)
     {
         try
         {
             _listener = new StreamSocketListener();
             _listener.ConnectionReceived += OnConnection;
             await _listener.BindServiceNameAsync(port);
         }
         catch (Exception e)
         {
             if (SocketError.GetStatus(e.HResult) == SocketErrorStatus.AddressAlreadyInUse)
             {
                 // Server is already running.
                 _listener.Dispose();
                 throw;
             }
             else if (SocketError.GetStatus(e.HResult) == SocketErrorStatus.Unknown)
             {
                 throw;
             }
         }
     }
 }
예제 #17
0
        protected override async void OnNavigatedTo(NavigationEventArgs e)
        {
            if (listener != null)
            {
                listener.ConnectionReceived -= OnConnReceived;
                listener.Dispose();
                listener = null;
            }

            listener = new StreamSocketListener();
            listener.ConnectionReceived += OnConnReceived;
            await listener.BindServiceNameAsync("");

            runPort.Text = listener.Information.LocalPort;

            //=========================================================
            var hosts = NetworkInformation.GetHostNames();

            foreach (HostName h in hosts)
            {
                if (h.IPInformation != null && h.Type == HostNameType.Ipv4)
                {
                    runIp.Text = h.DisplayName;
                    break;
                }
            }
        }
예제 #18
0
 public void Dispose()
 {
     if (listener != null)
     {
         listener.Dispose();
     }
 }
예제 #19
0
        private void Stop(bool stopListener)
        {
            if (InvokeRequired)
            {
                Invoke(new MethodInvoker(delegate
                {
                    Stop(stopListener);
                }));
                return;
            }

            if (socket != null)
            {
                socket.Dispose();
                socket = null;
            }

            if (stopListener && socketListener != null)
            {
                if (rfcommProvider != null)
                {
                    rfcommProvider.StopAdvertising();
                    rfcommProvider = null;
                }

                socketListener.Dispose();
                socketListener = null;

                startButton.Enabled = true;
                stopButton.Enabled  = false;
                status.Text         = "Stopped.";
            }
            sendButton.Enabled = false;
        }
예제 #20
0
        public void Stop()
        {
            _isRunning = false;

            _defaultEndpointSocket?.Dispose();
            _defaultEndpointSocket = null;
        }
예제 #21
0
        public async Task StartServerAsync()
        {
            if (listener != null)
            {
                listener.Dispose();
                listener = null;
            }

            if (listener == null)
            {
                listener = new StreamSocketListener();
                listener.ConnectionReceived += Listener_ConnectionReceived;
            }

            await listener.BindServiceNameAsync(port);
        }
예제 #22
0
        public async Task Stop()
        {
            await streamSocketListener.CancelIOAsync();

            streamSocketListener.Dispose();
            StoppedEventHandler?.Invoke(false);
        }
예제 #23
0
        public async void Start()
        {
            try
            {
                //Fecha a conexão com a porta que está escutando atualmente
                if (listener != null)
                {
                    await listener.CancelIOAsync();

                    listener.Dispose();
                    listener = null;
                }

                //Criar uma nova instancia do listerner
                listener = new StreamSocketListener();

                //Adiciona o evento de conexão recebida ao método Listener_ConnectionReceived
                listener.ConnectionReceived += Listener_ConnectionReceived;
                //Espera fazer o bind da porta
                await listener.BindServiceNameAsync(Port.ToString());

                Debug.WriteLine("listening");
            }
            catch (Exception e)
            {
                //Caso aconteça um erro, dispara o evento de erro
                if (OnError != null)
                {
                    OnError(e.Message);
                }
                Debug.WriteLine("error listen");
            }
        }
        public async void Start()
        {
            try
            {
                // Fecha a conexão com a porta que está escutando atualmente...
                if (listener != null)
                {
                    await listener.CancelIOAsync();

                    listener.Dispose();
                    listener = null;
                }

                // Cria uma nova instância do listener
                listener = new StreamSocketListener();

                // Adiciona o evento de conexão recebida ao método Listener_ConnectionReceived...
                listener.ConnectionReceived += Listener_ConnectionReceived;

                // Espera fazer o bind da porta...
                await listener.BindServiceNameAsync(Port.ToString());
            }
            catch (Exception e)
            {
                if (OnError != null)
                {
                    OnError(e.Message);
                }
            }
        }
 public void Disconnect()
 {
     Listening = false;
     if (provider != null)
     {
         if (isAdvertising)
         {
             provider.StopAdvertising();
         }
         provider = null;
     }                                                                                                      // StopAdvertising relentlessly causes a crash if not advertising.
     if (socketListener != null)
     {
         socketListener.Dispose(); socketListener = null;
     }
     if (writer != null)
     {
         writer.DetachStream(); writer.Dispose(); writer = null;
     }
     if (reader != null)
     {
         reader.DetachStream(); reader.Dispose(); reader = null;
     }
     if (socket != null)
     {
         socket.Dispose(); socket = null;
     }
     if (listeningTask != null)
     {
         listeningTask = null;
     }
 }
예제 #26
0
        public async void Star()
        {
            try
            {
                if (listener != null)
                {
                    await listener.CancelIOAsync();

                    listener.Dispose();
                    listener = null;
                }


                listener = new StreamSocketListener();

                listener.ConnectionReceived += Listener_ConnectionReceived;
                await listener.BindServiceNameAsync(Port.ToString());
            }
            catch (Exception e)
            {
                if (OnError != null)
                {
                    OnError(e.Message);
                }
            }
        }
예제 #27
0
        /// <summary>
        /// Start Socket Server
        /// </summary>
        public async Task Start()
        {
            try
            {
                if (_listener != null)
                {
                    await _listener.CancelIOAsync();

                    _listener.Dispose();
                    _listener = null;
                }
                _listener = new StreamSocketListener();

                _listener.ConnectionReceived += Listener_ConnectionReceived;
                //await _listener.BindServiceNameAsync(this._port.ToString());
                await _listener.BindEndpointAsync(new HostName(this._host), this._port.ToString());
            }
            catch (Exception e)
            {
                // Error Handler
                if (OnError != null)
                {
                    OnError(e.Message);
                }
            }
        }
예제 #28
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();
            }

            await this.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => this.serverListBox.Items.Add(string.Format("server received the request: \"{0}\"", request)));

            // 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();
                }
            }

            await this.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => this.serverListBox.Items.Add(string.Format("server sent back the response: \"{0}\"", request)));

            sender.Dispose();

            await this.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => this.serverListBox.Items.Add("server closed its socket"));
        }
예제 #29
0
 public void Dispose()
 {
     if (tcpListener != null)
     {
         tcpListener.Dispose();
     }
 }
예제 #30
0
 /// <inheritdoc />
 public void Stop()
 {
     _streamTcs?.TrySetCanceled();
     _streamTcs = null;
     _tokenRegistration.Dispose();
     _listener.ConnectionReceived -= OnConnectionReceived;
     _listener.Dispose();
 }