public async Task StopListener() { _streamSocketListener.ConnectionReceived -= StreamSocketListener_ConnectionReceived; await _streamSocketListener.CancelIOAsync(); _streamSocketListener = null; }
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"); } }
async void OnConnectionReceived(StreamSocketListener listener, StreamSocketListenerConnectionReceivedEventArgs args) { try { Log("Accepted."); provider.StopAdvertising(); await listener.CancelIOAsync(); StreamSocket socket = args.Socket; Log("Start connection."); var input_stream = socket.InputStream; while (true) { Windows.Storage.Streams.Buffer buffer = new Windows.Storage.Streams.Buffer(1024); var n = await input_stream.ReadAsync(buffer, buffer.Capacity, Windows.Storage.Streams.InputStreamOptions.Partial); byte[] bytes = buffer.ToArray(); String text = System.Text.Encoding.UTF8.GetString(bytes, 0, (int)n.Length); Log($"Received: {text}"); var notificationData = JsonConvert.DeserializeObject <NotificationData>(text); ShowNotification(notificationData.app_name, notificationData.title, notificationData.content); } } catch (Exception error) { Log(error.ToString()); } }
async void OnConnectionReceived(StreamSocketListener listener, StreamSocketListenerConnectionReceivedEventArgs args) { try { Debug.WriteLine("Received."); provider.StopAdvertising(); await listener.CancelIOAsync(); StreamSocket socket = args.Socket; Debug.WriteLine("Start connection."); var input_stream = socket.InputStream; while (true) { Windows.Storage.Streams.Buffer buffer = new Windows.Storage.Streams.Buffer(1024); var n = await input_stream.ReadAsync(buffer, buffer.Capacity, Windows.Storage.Streams.InputStreamOptions.Partial); byte[] bytes = buffer.ToArray(); String text = System.Text.Encoding.UTF8.GetString(bytes, 0, (int)n.Length); Debug.WriteLine($"Received: {text}"); ShowNotification("app_name", "title", text); } } catch (Exception error) { Debug.WriteLine(error.ToString()); } }
/// <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); } } }
public async Task Stop() { try { shouldStop = true; foreach (var client in this.serverClients) { await client.Stop(); } if (listener != null) { await listener.CancelIOAsync(); } this.IsConnected = false; } catch (Exception ex) { System.Exception exNew = new System.Exception(string.Format("Exception In: {0}", CallerName()), ex); this.Notifyexception(exNew); throw exNew; } }
/// <summary> /// Constructor /// </summary> /// <param name="serverPort">Port to start server on</param> internal WebServer(StartupTask st, int serverPort) { _startupTask = st; _webhelper = new WebHelper(); _devices = new Devices(); _listener = new StreamSocketListener(); _webApiHelper = new WebApiHelper(); _port = serverPort; _listener.ConnectionReceived += (s, e) => { try { if (_startupTask.IsClosing) { _listener.CancelIOAsync().GetResults(); } else { // Process incoming request processRequestAsync(e.Socket); } } catch (Exception ex) { Debug.WriteLine("Exception in StreamSocketListener.ConnectionReceived(): " + ex.Message); } }; }
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 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); } } }
public async Task Stop() { await streamSocketListener.CancelIOAsync(); streamSocketListener.Dispose(); StoppedEventHandler?.Invoke(false); }
public void Dispose() { if (listener != null) { listener.CancelIOAsync().AsTask().Wait(); listener.Dispose(); } }
private void DisposeSocketListener() { if (socketListener != null) { socketListener.CancelIOAsync().GetAwaiter().GetResult(); socketListener.Dispose(); socketListener = null; } }
public async Task TransferOwnership() { if (_streamSocketListener != null) { await _streamSocketListener.CancelIOAsync(); _streamSocketListener.TransferOwnership("StreamSocket"); } }
public async Task StopListening() { if (socketListener != null) { CancelSocketTask(); await socketListener.CancelIOAsync().AsTask().ConfigureAwait(false); socketListener.Dispose(); socketListener = null; ConnectionStatus = ConnectionStatus.Disconnected; } }
public async Task CloseAsync() { if (_listener == null) { return; } //To Stop Read _cancel.Cancel(); await _socket.CancelIOAsync(); await _listener.CancelIOAsync(); }
private async void StopServer() { if (_streamSocketListener == null) { return; } _streamSocketListener.ConnectionReceived -= StreamSocketListener_ConnectionReceived; await _streamSocketListener.CancelIOAsync(); _streamSocketListener.Dispose(); }
private async void buttonRegister_Click(object sender, RoutedEventArgs e) { try { //タスクがすでに登録されている場合は解除する foreach (var t in BackgroundTaskRegistration.AllTasks) { t.Value.Unregister(true); } //バックグラウンドタスクを登録する //NameはなんでもいいけどTaskEntryPointはバックグランドタスクの {名前空間}.{クラス名} にしないとだめ var socketTaskBuilder = new BackgroundTaskBuilder(); socketTaskBuilder.Name = "MySocketBackgroundTask"; socketTaskBuilder.TaskEntryPoint = "BackgroundSocketComponent.SocketListenTask"; //バックグラウンドタスクでSocketを待ち受けるためのトリガー //これのおかげでバックグラウンドタスクがSocketに反応できる var trigger = new SocketActivityTrigger(); socketTaskBuilder.SetTrigger(trigger); var task = socketTaskBuilder.Register(); //ソケットリスナー var socketListener = new StreamSocketListener(); var hostname = NetworkInformation.GetHostNames().Where(q => q.Type == HostNameType.Ipv4).First(); var port = textPort.Text; //バックグラウンドタスクとポート番号を合わせるためにローカル設定に入れておく ApplicationData.Current.LocalSettings.Values["SocketPort"] = port; //バックグラウンドタスクとソケットIDを合わせるためにローカル設定に入れておく ApplicationData.Current.LocalSettings.Values["SocketId"] = socketId; //バックグラウンドタスクにソケットリスナーの権限を渡すことを許可 //第2引数はDoNotWakeにしないとBind時にエラーになる socketListener.EnableTransferOwnership(task.TaskId, SocketActivityConnectedStandbyAction.DoNotWake); //ホスト名とポート番号でバインドする await socketListener.BindEndpointAsync(hostname, port); //ここから下はSuspendingイベントに入れてもいい //ソケットリスナーをバックグランドタスクに渡すためにIOを止める await socketListener.CancelIOAsync(); //バックグランドタスクに権限を渡す socketListener.TransferOwnership(socketId); var dialog = new MessageDialog("Complete to register backgroundtask and to start listen socket!"); await dialog.ShowAsync(); }catch (Exception ex) { var dialog = new MessageDialog(ex.Message); await dialog.ShowAsync(); } }
/// <summary> /// Disposes of the TCP socket and sets it to null. Returns false if /// you weren't listening. /// </summary> public async Task <bool> StopListening() { if (_localSocket != null) { await _localSocket.CancelIOAsync(); _localSocket.ConnectionReceived -= LocalSocketConnectionReceived; _localSocket.Dispose(); _localSocket = null; return(true); } return(false); }
private async Task StopServer() { if (!_isServerStarted) { return; } Debug.WriteLine("************* STOPPING SERVER *****************"); _listener.ConnectionReceived -= receivedConnectionHandler; await _listener.CancelIOAsync(); _listener.Dispose(); StreamingButton.Foreground = new SolidColorBrush(Colors.DarkGray); _isServerStarted = false; }
/// <summary> /// Disposes of the TCP socket and sets it to null. Returns false if /// you weren't listening. /// </summary> public async Task <bool> StopListening() { bool status = false; if (_localSocket != null) { await _localSocket.CancelIOAsync(); _localSocket.ConnectionReceived -= LocalSocketConnectionReceived; _localSocket.Dispose(); _localSocket = null; status = true; } return(status); }
async void OnConnectionReceived( StreamSocketListener listener, StreamSocketListenerConnectionReceivedEventArgs args) { // Stop advertising/listening so that we're only serving one client _provider.StopAdvertising(); await listener.CancelIOAsync(); //.Close(); _socket = args.Socket; // The client socket is connected. At this point the App can wait for // the user to take some action, e.g. click a button to receive a file // from the device, which could invoke the Picker and then save the // received file to the picked location. The transfer itself would use // the Sockets API and not the Rfcomm API, and so is omitted here for // brevity. }
public override async void Dispose() { Working = false; await SendMsg(new MessageModel { IsDisConnected = true }); foreach (var clientSocket in ClientSockets) { clientSocket.Dispose(); } ClientSockets.Clear(); ClientSockets = null; Listener.ConnectionReceived -= OnConnection; Listener?.CancelIOAsync(); Listener.Dispose(); Listener = null; }
/// <summary> /// Stop the current server /// </summary> /// <returns></returns> private async Task StopServer() { StreamSocketListener lastNetworkListener = null; lock (stateLock) { lastNetworkListener = networkListener; networkListener = null; serverBuffer = null; } if (lastNetworkListener != null) { lastNetworkListener.ConnectionReceived -= ConnectionReceived; await lastNetworkListener.CancelIOAsync(); lastNetworkListener.Dispose(); } }
/// <summary> /// Stops the service listener if in started state. /// </summary> public async void StopAsync() { try { if (!IsActive) { _logger.Info("Listener is not active and must be started before stopping"); return; } await _listener.CancelIOAsync(); IsActive = false; _logger.Info("Stopped listening for requests on {0}", _listener.Information.LocalPort); } catch (Exception ex) { _logger.Error("Stopping listener Failed: {0}", ex.Message.ToString(), ex); } }
/// <summary> /// Close connection /// </summary> /// <returns></returns> public async Task CloseConnection() { // Stop Hearbeat _dispatcherServerHeartbeatTimer.Stop(); // Request cancellation if (_cts != null) { _cts.Cancel(); _cts.Dispose(); _cts = null; } // Close connection. if (_listener != null) { await _listener.CancelIOAsync(); _listener.Dispose(); _listener = null; } _activeHost = null; }
public Task StopServerAsync() => listener.CancelIOAsync().AsTask();
public async void Run(IBackgroundTaskInstance taskInstance) { var deferral = taskInstance.GetDeferral(); if (taskInstance.TriggerDetails is SocketActivityTriggerDetails) { try { //ソケットIDを取得 var socketId = ApplicationData.Current.LocalSettings.Values["SocketId"].ToString(); var details = taskInstance.TriggerDetails as SocketActivityTriggerDetails; var socketInformation = details.SocketInformation; switch (details.Reason) { //コネクションがアクセプトされたなら(自動でアクセプトされる) case SocketActivityTriggerReason.ConnectionAccepted: //SocketInformationにはStreamSocketに値がある場合とStreamSocketListenerの2パターンがあるのでSocketKindで判別 if (socketInformation.SocketKind == SocketActivityKind.StreamSocketListener) { //StreamSocketListenerを取得 var socket = socketInformation.StreamSocketListener; //AcceptされたSocketがこのイベントで取得できるがこのイベントが発火するまでプロセスを落としてはいけないので //Task.Delayで2秒ぐらい待つ socket.ConnectionReceived += (s, e) => { //アクセプトされたソケットを取得したらソケットリスナー登録時同様、このタスクにソケットを受信できるように設定 var socketClient = e.Socket; socketClient.EnableTransferOwnership(taskInstance.Task.TaskId); socketClient.TransferOwnership(socketId); ShowToast(string.Format("Connect {0}", socketClient.Information.LocalAddress.DisplayName)); //ソケットリスナーは破棄しないと次回リスナー起動時に死ぬ socketInformation.StreamSocketListener.Dispose(); }; await Task.Delay(2000); } break; case SocketActivityTriggerReason.KeepAliveTimerExpired: socketInformation.StreamSocket.TransferOwnership(socketId); break; //ソケットにデータが来た時 case SocketActivityTriggerReason.SocketActivity: //1バイト読んでトーストで表示 using (var reader = new DataReader(socketInformation.StreamSocket.InputStream)) { uint readNum = 1; await reader.LoadAsync(readNum); var data = reader.ReadString(readNum); ShowToast(string.Format("DataReceived {0}", data.ToString())); } socketInformation.StreamSocket.TransferOwnership(socketId); break; //ソケットが閉じられたとき case SocketActivityTriggerReason.SocketClosed: //ソケットが閉じられたとき、以下の処理を読んで再度リッスンすればよいが //OSが再起動したとき、SocketClosedが2回呼ばれる(謎) //2回の呼び出しの違いはSocketの数なのでSocketの数で1回目を判定して再度リッスン if (SocketActivityInformation.AllSockets.Count == 0) { var socketListener = new StreamSocketListener(); var hostname = NetworkInformation.GetHostNames().Where(q => q.Type == HostNameType.Ipv4).First(); var port = ApplicationData.Current.LocalSettings.Values["SocketPort"].ToString(); socketListener.EnableTransferOwnership(taskInstance.Task.TaskId, SocketActivityConnectedStandbyAction.DoNotWake); await socketListener.BindEndpointAsync(hostname, port); await socketListener.CancelIOAsync(); socketListener.TransferOwnership(socketId); ShowToast(string.Format("{0}:{1} restart socket listen", hostname, port)); } break; } } catch (Exception e) { ShowToast("error = " + e.Message + " " + e.StackTrace); } } deferral.Complete(); }
public async void Dispose() { await _streamSocketListener.CancelIOAsync(); _streamSocketListener.Dispose(); }
public async void Stop() { await listener.CancelIOAsync(); listener.Dispose(); }