private async void StartButton_Click(Object sender, RoutedEventArgs e) { StreamSocketListener listener = new StreamSocketListener(); listener.ConnectionReceived += Listener_ConnectionReceived; capture = new UWPVideoCaptureHelper(); try { MediaCaptureInitializationSettings settings = await GetMediaCaptureSettingsAsync(Windows.Devices.Enumeration.Panel.Back, (int)Preview.Width, (int)Preview.Height, 30); await listener.BindEndpointAsync(new HostName("127.0.0.1"), "25"); capturing = true; bool result = await capture.Start(settings, (int)Preview.Width, (int)Preview.Height, 25); System.Diagnostics.Debug.WriteLine("Capture start returned " + result); } catch (System.Runtime.InteropServices.COMException cex) { var error = cex.HResult; } }
private async void onInitiated() { videoPort = "8900"; jsonPort = "8988"; rootFolder = ApplicationData.Current.LocalFolder; connectionHappened = false; isTextureLoaded = false; tabletResX = 640; tabletResY = 400;//400 for tablet //480 for drone orgNumChan = 3; targetNumChan = 4; orgRes = tabletResX * tabletResY * orgNumChan; targetRes = tabletResX * tabletResY * targetNumChan; g_StreamInfo = new byte[orgRes]; g_NewBytes = new byte[targetRes]; g_TempTex = new Texture2D((int)tabletResX, (int)tabletResY, TextureFormat.RGBA32, false); tcpVideoListener = new StreamSocketListener(); tcpVideoListener.ConnectionReceived += onConnected; await tcpVideoListener.BindEndpointAsync(null, videoPort); tcpJsonListener = new StreamSocketListener(); tcpJsonListener.ConnectionReceived += jsonOnConnected; await tcpJsonListener.BindEndpointAsync(null, jsonPort); }
/// <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); } } }
/// <summary> /// Function for starting the listening for messages. /// </summary> /// <param name="port">The port to listen on.</param> public async void StartSockets(int tcpPort, int udpPort) { _tcpListener = new StreamSocketListener(); _tcpListener.Control.KeepAlive = true; _tcpListener.ConnectionReceived += ConnectionReceived; _udpSocket = new DatagramSocket(); _udpSocket.MessageReceived += LeapDataReceived; _localHostName = GetIpv4HostName(); try { await _tcpListener.BindEndpointAsync(_localHostName, tcpPort.ToString()); Debug.LogFormat("Bound TCP-socket to endpoint {0}/{1}", _localHostName.ToString(), tcpPort.ToString()); await _udpSocket.BindEndpointAsync(_localHostName, udpPort.ToString()); Debug.LogFormat("Bound UDP-socket to endpoint {0}/{1}", _localHostName.ToString(), udpPort.ToString()); _currentText.Value = "Sockets bound. Ready to calibrate."; } catch (Exception e) { Debug.LogException(e); } }
public override async Task Start() { try { if (Working) { return; } IsServer = true; ClientSockets = new List <StreamSocket>(); Listener = new StreamSocketListener() { Control = { KeepAlive = false } }; Listener.ConnectionReceived += OnConnection; var hostname = new HostName(IpAddress); await Listener.BindEndpointAsync(hostname, RemoteServiceName); Working = true; OnStartSucess?.Invoke(); } catch (Exception e) { OnStartFailed?.Invoke(e); } }
/// <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); } } }
/// <inheritdoc /> public async Task StartAsync() { _listener = new StreamSocketListener(); _listener.ConnectionReceived += OnConnectionReceived; await _listener.BindEndpointAsync(_ipAddress, _port).AsTask().ConfigureAwait(false); }
public async void Start() { lock (this) { if (Running) { throw new InvalidOperationException("Server is already running."); } Running = true; } m_listeners = new List <StreamSocketListener>(); StreamSocketListener listener; foreach (HostName candidate in NetworkInformation.GetHostNames()) { if ((candidate.Type == HostNameType.Ipv4) || (candidate.Type == HostNameType.Ipv6)) { listener = new StreamSocketListener(); listener.ConnectionReceived += OnConnectionReceived; await listener.BindEndpointAsync(candidate, Port.ToString()); m_listeners.Add(listener); } } }
protected override async void OnNavigatedTo(NavigationEventArgs e) { rootPage = MainPage.Current; rootPage.NotifyUser("Waiting for client to connect...", NotifyType.StatusMessage); tcpListener = new StreamSocketListener(); tcpListener.ConnectionReceived += OnConnected; await tcpListener.BindEndpointAsync(null, port); }
/// <summary> /// 连接者套接字建立 /// </summary> /// <param name="deviceId"></param> /// <param name="port"></param> async void EstablishSocketFromAdvertiser(HostName hostName, string port) { StreamSocketListener listener = new StreamSocketListener(); listener.ConnectionReceived += OnConnectionReceived; await listener.BindEndpointAsync(hostName, port); Invoke(() => { TextBlock_ConnectedState.Text = "成功与设备" + EndpointPairs[0].LocalHostName.ToString() + "建立接口"; }); }
// public methods public async Task <Int32> bind(string address, Int32 port) { _socketListener = new StreamSocketListener(); _socketListenerLocalAddress = address; _socketListener.ConnectionReceived += _socket_ConnectionReceived; await _socketListener.BindEndpointAsync(new HostName(address), port.ToString()); return(0); }
private async Task <bool> HandleConnectionRequestAsync(WiFiDirectConnectionRequest connectionRequest) { string deviceName = connectionRequest.DeviceInformation.Name; bool isPaired = (connectionRequest.DeviceInformation.Pairing?.IsPaired == true) || (await IsAepPairedAsync(connectionRequest.DeviceInformation.Id)); //rootPage.NotifyUser($"Connecting to {deviceName}...", NotifyType.StatusMessage); // Pair device if not already paired and not using legacy settings if (!isPaired && !_publisher.Advertisement.LegacySettings.IsEnabled) { if (!await connectionSettingsPanel.RequestPairDeviceAsync(connectionRequest.DeviceInformation.Pairing)) { return(false); } } WiFiDirectDevice wfdDevice = null; try { // IMPORTANT: FromIdAsync needs to be called from the UI thread wfdDevice = await WiFiDirectDevice.FromIdAsync(connectionRequest.DeviceInformation.Id); } catch (Exception ex) { //rootPage.NotifyUser($"Exception in FromIdAsync: {ex}", NotifyType.ErrorMessage); return(false); } // Register for the ConnectionStatusChanged event handler //wfdDevice.ConnectionStatusChanged += OnConnectionStatusChanged; StreamSocketListener listenerSocket = new StreamSocketListener(); // Save this (listenerSocket, wfdDevice) pair so we can hook it up when the socket connection is made. _pendingConnections[listenerSocket] = wfdDevice; IReadOnlyList <Windows.Networking.EndpointPair> EndpointPairs = wfdDevice.GetConnectionEndpointPairs(); listenerSocket.ConnectionReceived += OnSocketConnectionReceived; try { await listenerSocket.BindEndpointAsync(EndpointPairs[0].LocalHostName, Globals.strServerPort); } catch (Exception ex) { //rootPage.NotifyUser($"Connect operation threw an exception: {ex.Message}", NotifyType.ErrorMessage); return(false); } //rootPage.NotifyUser($"Devices connected on L2, listening on IP Address: {EndpointPairs[0].LocalHostName}" + //$" Port: {Globals.strServerPort}", NotifyType.StatusMessage); return(true); }
protected override async void OnNavigatedTo(NavigationEventArgs e) { Debug.WriteLine("Waiting for client to connect..."); tcpVideoListener = new StreamSocketListener(); tcpVideoListener.ConnectionReceived += OnConnected; await tcpVideoListener.BindEndpointAsync(null, videoPort); tcpJsonListener = new StreamSocketListener(); tcpJsonListener.ConnectionReceived += jsonOnConnected; await tcpJsonListener.BindEndpointAsync(null, jsonPort); }
public async Task InitServer() { localHostName = new HostName(hostname); listener = new StreamSocketListener(); listener.ConnectionReceived += (ss, ee) => { ServerSocket = ee.Socket; }; await listener.BindEndpointAsync(localHostName, port); }
public async Task Start(string iface, int port) { try { streamSocketListener = new StreamSocketListener(); streamSocketListener.ConnectionReceived += StreamSocketListener_ConnectionReceived; await streamSocketListener.BindEndpointAsync(new Windows.Networking.HostName(iface), port.ToString()); } catch (Exception ex) { throw ex; } }
public static async void StartAsync() { int port = Config.Ports.ClientServerConnection; listener = new StreamSocketListener(); SetSocketSettings(listener.Control); listener.ConnectionReceived += OnConnection; // Bind TCP to the server endpoint HostName serverHostName = new HostName(IPManager.GetLocalIpAddress()); int serverPort = Config.Ports.ClientServerConnection; await listener.BindEndpointAsync(serverHostName, serverPort.ToString()); }
public void StartConnectionListener(string localAddress, string remoteAddress, string localPort) { if (localAddress == null) { throw new ArgumentNullException("localAddress"); } if (remoteAddress == null) { throw new ArgumentNullException("remoteAddress"); } if (localPort == null) { throw new ArgumentNullException("localPort"); } lock (this.criticalSection) { if (this.streamSocketListener != null) { throw new InvalidOperationException("The stream socket listener is already running"); } if (this.streamSocket != null) { throw new InvalidOperationException("A stream socket is already connected"); } WiFiDirectTestLogger.Log("Listening for incoming TCP connection. Local Address = {0}, Remote Address = {1}, Local Port={2}", localAddress, remoteAddress, localPort); this.expectedRemoteHost = new HostName(remoteAddress); StreamSocketListener streamSocketListener = new StreamSocketListener(); try { streamSocketListener.ConnectionReceived += this.ConnectionReceived; streamSocketListener.BindEndpointAsync(new HostName(localAddress), localPort).AsTask().Wait(); this.streamSocketListener = streamSocketListener; streamSocketListener = null; } finally { if (streamSocketListener != null) { 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(); } }
private async Task StartListener() { Debug.WriteLine($"Starting listener"); _listener = new StreamSocketListener(); _listener.ConnectionReceived += (sender, args) => { Debug.WriteLine($"Connection received from {args.Socket.Information.RemoteAddress}"); _connections.Add(new Connection(args.Socket, this)); }; HostName host = NetworkInformation.GetHostNames().FirstOrDefault(x => x.IPInformation != null && x.Type == HostNameType.Ipv4); await _listener.BindEndpointAsync(host, $"{_port}"); Debug.WriteLine($"Listener started on {host.DisplayName}:{_listener.Information.LocalPort}"); }
public async Task start(string hostname, string servicename) { try { HostName hostName = new HostName(hostname); await listener.BindEndpointAsync(hostName, 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; } } }
/// <summary> /// Start listener /// </summary> /// <param name="p_host"></param> /// <param name="p_port"></param> /// <param name="p_password"></param> /// <returns></returns> public async Task <StreamSocketListener> StartListener(Host p_host, String p_port, String p_password) { // Set encryption password if (p_password.Length < 6) { throw new System.ArgumentException("Passphrase must be at least 6 characters"); } _password = p_password; // Bind a new end point if a different host is selected or if the local port is not bound or is changed if (_activeHost == null || _activeHost.Name != p_host.Name || _listener == null || _listener.Information == null || _listener.Information.LocalPort != p_port) { // Cancel current connection if it exists await CloseConnection(); //Create a new Cancel Token and socket listener _cts = new CancellationTokenSource(); _listener = new StreamSocketListener(); //Assigned event when have a new connection _listener.ConnectionReceived += Listener_ConnectionReceived; //Bind port await _listener.BindEndpointAsync(p_host.Name, p_port); _activeHost = p_host; // Initiate a client connection to the server for testing the connection is still open var connIinit = await _serverClient.ConnectAsync(p_host.DisplayString, _listener.Information.LocalPort, p_password); // Start timer, send heartbeat periodically if (_dispatcherServerHeartbeatTimer != null) { _dispatcherServerHeartbeatTimer.Start(); } } else { throw new ListenerAlreadyRunningException("Listener already started on " + p_host.DisplayString + ", port " + p_port); } return(_listener); }
public async void StartServer() { try { //get IP var icp = NetworkInformation.GetInternetConnectionProfile(); if (icp != null && icp.NetworkAdapter != null) { var hostname = NetworkInformation.GetHostNames() .SingleOrDefault( hn => hn.IPInformation != null && hn.IPInformation.NetworkAdapter != null && hn.IPInformation.NetworkAdapter.NetworkAdapterId == icp.NetworkAdapter.NetworkAdapterId); if (hostname != null) { // the ip address this.ipAddress = hostname.CanonicalName; this.txtBoxAddress.Text = hostname.CanonicalName; } } listener = new StreamSocketListener(); listener.ConnectionReceived += OnConnection; // 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. listener.Control.KeepAlive = false; // Try to bind to a specific address. await listener.BindEndpointAsync(new HostName(txtBoxAddress.Text), ServiceName); rootPage.ShowMessage("Listening"); } 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) { rootPage.ShowMessage( "Start listening failed with error: " + exception.Message); } } }
protected async override void OnNavigatedTo(NavigationEventArgs e) { base.OnNavigatedTo(e); await _listener.BindEndpointAsync(_host, $"{_port}"); await Task.Run(async() => { _client = new StreamSocket(); await _client.ConnectAsync(_host, $"{_port}"); int command = 1; byte[] cmd = BitConverter.GetBytes(command); byte[] path = Encoding.UTF8.GetBytes(@"C:\Users\Dave\Music\Offaiah-Trouble_(Club_Mix).mp3"); byte[] length = BitConverter.GetBytes(path.Length); byte[] result = cmd.Concat(length.Concat(path)).ToArray(); await _client.OutputStream.WriteAsync(result.AsBuffer()); }); }
public MainPage() { this.InitializeComponent(); Window.Current.CoreWindow.KeyDown += CoreWindow_KeyDown; Window.Current.CoreWindow.KeyUp += CoreWindow_KeyUp; keyHandler = new KeyHandler(this); cameraServer = new CameraServer(UpdateImageAsync); // Not using MVVM here, directly using imperative code to change image source MovementController movementController = new MovementController(); Task.Factory.StartNew(movementController.MonitorForMovement); StreamSocketListener listener = new StreamSocketListener(); listener.BindEndpointAsync(new HostName(SELF_IP_ADDRESS), SELF_CAMERA_PORT); // It's okay to not use await here because we can register an event handler before the endpoint is bounded listener.ConnectionReceived += Listener_ConnectionReceived; }
/// <summary> /// This is the click handler for the 'StartListener' button. /// </summary> public static async void StartListener() { listener = new StreamSocketListener(); listener.ConnectionReceived += OnConnection; // 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. listener.Control.KeepAlive = false; // Start listen operation. var hostName = NetworkDataSender.GetAdapter(); if (hostName != null) { await listener.BindEndpointAsync(hostName, ServiceNameForListener); } }
private async Task <int> getLocalPort() { int tries = 0; int port = 25; Random rand = new Random((int)DateTime.Now.Ticks); while (tries < 10) { try { tries++; await listener.BindEndpointAsync(new HostName("127.0.0.1"), port.ToString()); return(port); } catch { port = rand.Next(1, 65535); } } return(0); }
public async void InitServer() { try { _localHost = NetworkInformation.GetHostNames().Where(q => q.Type == HostNameType.Ipv4).First(); _listener = new StreamSocketListener(); _listener.ConnectionReceived += (ss, ee) => { _serverSocket = ee.Socket; Debug.WriteLine("connected {0}", _serverSocket.Information.RemoteAddress); this.UpdateStatusMessage(String.Format("connected {0}", _serverSocket.Information.RemoteAddress)); _writer = new DataWriter(_serverSocket.OutputStream); }; await _listener.BindEndpointAsync(_localHost, _port); Debug.WriteLine("listen..."); this.UpdateStatusMessage("listen..."); } catch (Exception ex) { Debug.WriteLine("InitServer Failure : {0}", ex.ToString()); } }
private async Task CreateListener() { HostName hostName; if (!CoreApplication.Properties.ContainsKey("listener")) { try { StreamSocketListener listener = new StreamSocketListener(); listener.Control.KeepAlive = false; listener.ConnectionReceived += OnRecieved; hostName = LoadIpInfo(); await listener.BindEndpointAsync(hostName, App.ServiceName); CoreApplication.Properties.Add("listener", listener); CoreApplication.Properties.Add("host", hostName); } catch (Exception ex) { await new MessageDialog(ex.Message).ShowAsync(); } } }
/// <summary> /// Initializes the new server object and puts it in listening mode /// </summary> /// <param name="rules">Set of rules in a form "URL Reg-ex" => "Method to be fired when rule is met"</param> /// <param name="ip">IP to bind to</param> /// <param name="port">Port to bind to</param> public WebServer(Dictionary <Regex, RuleDeletage> rules, string ip, string port) { // Assign passed rules to the server _serverRules = rules; try { // Try to turn on the server Task.Run(async() => { // Start listening _listener.ConnectionReceived += listener_ConnectionReceived; // Bind to IP:Port await _listener.BindEndpointAsync(new HostName(ip), port); IsListening = true; }); } catch (Exception ex) { // If possible fire the error event with the exception message ErrorOccured?.Invoke(-1, ex.Message); } }
/// <summary> /// StartListener /// </summary> /// <returns></returns> public async Task Start() { shouldStop = false; listener = new StreamSocketListener(); HostName hostName; hostName = new HostName(this.HostNameOrIp); listener.ConnectionReceived += OnConnection; // 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. listener.Control.KeepAlive = false; // Don't limit traffic to an address or an adapter. //await listener.BindServiceNameAsync(localServiceName); await listener.BindEndpointAsync(hostName, this.Port); this.IsConnected = true; }