private async Task run(string host, int port) { var listener = new StreamSocketListener(); listener.ConnectionReceived += listener_ConnectionReceived; await listener.BindEndpointAsync(new HostName(host), port.ToString()); }
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> /// Opens a connection, which means, that the server will be listening for telemetry clients to connect. /// </summary> /// <param name="strHostName">Hostname of the server.</param> /// <param name="strConnectionPort">Port which will be used for listening.</param> public async void OpenConnection(string strHostName, string strConnectionPort) { m_pTelemetryReaderSemaphoreSlim = new SemaphoreSlim(0, 1); m_pTcpListener = new StreamSocketListener(); m_pTcpListener.ConnectionReceived += OnConnectionReceived; m_pTcpListener.Control.KeepAlive = true; var localHostName = new HostName(strHostName); await m_pTcpListener.BindEndpointAsync(localHostName, strConnectionPort); }
private async void StartListener() { try { StreamSocketListener listener = new StreamSocketListener(); listener.ConnectionReceived += OnConnection; HostName name = new HostName("192.168.1.196"); await listener.BindEndpointAsync(name, "5656"); } 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; } } }
public async void Start(int port) { lock (this) { if (m_running) throw new InvalidOperationException("Server is already running."); m_running = true; } Port = port; 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); } } }
/// <summary> /// This is the click handler for the 'StartListener' button. /// </summary> /// <param name="sender">Object for which the event was generated.</param> /// <param name="e">Event's parameters.</param> private async void StartListener_Click(object sender, RoutedEventArgs e) { // Overriding the listener here is safe as it will be deleted once all references to it are gone. // However, in many cases this is a dangerous pattern to override data semi-randomly (each time user // clicked the button) so we block it here. if (CoreApplication.Properties.ContainsKey("listener")) { rootPage.NotifyUser( "This step has already been executed. Please move to the next one.", NotifyType.ErrorMessage); return; } if (String.IsNullOrEmpty(ServiceNameForListener.Text)) { rootPage.NotifyUser("Please provide a service name.", NotifyType.ErrorMessage); return; } CoreApplication.Properties.Remove("serverAddress"); CoreApplication.Properties.Remove("adapter"); LocalHostItem selectedLocalHost = null; if ((BindToAddress.IsChecked == true) || (BindToAdapter.IsChecked == true)) { selectedLocalHost = (LocalHostItem)AdapterList.SelectedItem; if (selectedLocalHost == null) { rootPage.NotifyUser("Please select an address / adapter.", NotifyType.ErrorMessage); return; } // The user selected an address. For demo purposes, we ensure that connect will be using the same // address. CoreApplication.Properties.Add("serverAddress", selectedLocalHost.LocalHost.CanonicalName); } StreamSocketListener listener = new StreamSocketListener(); listener.ConnectionReceived += OnConnection; // Save the socket, so subsequent steps can use it. CoreApplication.Properties.Add("listener", listener); // Start listen operation. try { if (BindToAny.IsChecked == true) { // Don't limit traffic to an address or an adapter. await listener.BindServiceNameAsync(ServiceNameForListener.Text); rootPage.NotifyUser("Listening", NotifyType.StatusMessage); } else if (BindToAddress.IsChecked == true) { // Try to bind to a specific address. await listener.BindEndpointAsync(selectedLocalHost.LocalHost, ServiceNameForListener.Text); rootPage.NotifyUser( "Listening on address " + selectedLocalHost.LocalHost.CanonicalName, NotifyType.StatusMessage); } else if (BindToAdapter.IsChecked == true) { // Try to limit traffic to the selected adapter. // This option will be overriden by interfaces with weak-host or forwarding modes enabled. NetworkAdapter selectedAdapter = selectedLocalHost.LocalHost.IPInformation.NetworkAdapter; // For demo purposes, ensure that use the same adapter in the client connect scenario. CoreApplication.Properties.Add("adapter", selectedAdapter); await listener.BindServiceNameAsync( ServiceNameForListener.Text, SocketProtectionLevel.PlainSocket, selectedAdapter); rootPage.NotifyUser( "Listening on adapter " + selectedAdapter.NetworkAdapterId, NotifyType.StatusMessage); } } catch (Exception exception) { CoreApplication.Properties.Remove("listener"); // 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; } rootPage.NotifyUser( "Start listening failed with error: " + exception.Message, NotifyType.ErrorMessage); } }
private async Task Initialize(Uri baseUri, SuperCacheConfig configuration) { this.baseUri = baseUri; this.configuration = configuration; activityId = Guid.NewGuid(); Trace.TraceLevel = configuration.TraceLevel; Trace.Information(activityId, "Server is starting..."); HostName hostName = null; string port = string.Empty; if (!configuration.ProxyUri.Equals(SuperCacheConfig.AutomaticProxyUriConfiguration, StringComparison.OrdinalIgnoreCase)) { // use manual configuration Uri proxyUri; if (!Uri.TryCreate(configuration.ProxyUri, UriKind.Absolute, out proxyUri)) { throw new InvalidOperationException("An invalid value was specified for the ProxyUri configuration setting."); } hostName = new HostName(proxyUri.Host); port = proxyUri.Port.ToString(); } // start socket listener listener = new StreamSocketListener(); listener.ConnectionReceived += (sender, args) => { Task.Run(async () => { await OnConnectionReceivedAsync(sender, args); }); }; await listener.BindEndpointAsync(hostName, port); // build proxy URI from the actual port bound to the listener this.proxyUri = new Uri( "http://" + (hostName != null ? hostName.CanonicalName : LocalhostIpAddress) + ":" + listener.Information.LocalPort); // initialize cookie manager cookieManager = new CookieManager(this.proxyUri); await cookieManager.LoadCookiesAsync(activityId); // initialize list of preload scripts await InitializePreloadScriptsAsync(); Trace.Information(activityId, "Server is listening on port: {0} - baseUri: {1}", listener.Information.LocalPort, this.baseUri); }
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); } } }
/// <summary> /// Start listening for data /// </summary> public void Start() { if (!mIsActive) { mIsActive = true; listener = new StreamSocketListener(); listener.Control.QualityOfService = SocketQualityOfService.Normal; listener.ConnectionReceived += Listener_ConnectionReceived; listener.BindEndpointAsync(new HostName(PeerConnector.GetMyIP()), listenerPort).AsTask().Wait(); } }
private async void OnConnectionRequested(WiFiDirectConnectionListener sender, WiFiDirectConnectionRequestedEventArgs connectionEventArgs) { try { var connectionRequest = connectionEventArgs.GetConnectionRequest(); var tcs = new TaskCompletionSource<bool>(); var dialogTask = tcs.Task; var messageDialog = new MessageDialog("Connection request received from " + connectionRequest.DeviceInformation.Name, "Connection Request"); // Add commands and set their callbacks; both buttons use the same callback function instead of inline event handlers messageDialog.Commands.Add(new UICommand("Accept", null, 0)); messageDialog.Commands.Add(new UICommand("Decline", null, 1)); // Set the command that will be invoked by default messageDialog.DefaultCommandIndex = 1; // Set the command to be invoked when escape is pressed messageDialog.CancelCommandIndex = 1; await Dispatcher.RunAsync(CoreDispatcherPriority.High, async () => { // Show the message dialog var commandChosen = await messageDialog.ShowAsync(); tcs.SetResult((commandChosen.Label == "Accept") ? true : false); }); var fProceed = await dialogTask; if (fProceed == true) { var tcsWiFiDirectDevice = new TaskCompletionSource<WiFiDirectDevice>(); var wfdDeviceTask = tcsWiFiDirectDevice.Task; await Dispatcher.RunAsync(CoreDispatcherPriority.High, async () => { try { rootPage.NotifyUser("Connecting to " + connectionRequest.DeviceInformation.Name + "...", NotifyType.StatusMessage); WiFiDirectConnectionParameters connectionParams = new WiFiDirectConnectionParameters(); connectionParams.GroupOwnerIntent = Convert.ToInt16(txtGOIntent.Text); // IMPORTANT: FromIdAsync needs to be called from the UI thread tcsWiFiDirectDevice.SetResult(await WiFiDirectDevice.FromIdAsync(connectionRequest.DeviceInformation.Id, connectionParams)); } catch (Exception ex) { rootPage.NotifyUser("FromIdAsync task threw an exception: " + ex.ToString(), NotifyType.ErrorMessage); } }); WiFiDirectDevice wfdDevice = await wfdDeviceTask; // Register for the ConnectionStatusChanged event handler wfdDevice.ConnectionStatusChanged += OnConnectionStatusChanged; await Dispatcher.RunAsync(CoreDispatcherPriority.High, () => { ConnectedDevice connectedDevice = new ConnectedDevice("Waiting for client to connect...", wfdDevice, null); _connectedDevices.Add(connectedDevice); }); var EndpointPairs = wfdDevice.GetConnectionEndpointPairs(); _listenerSocket = null; _listenerSocket = new StreamSocketListener(); _listenerSocket.ConnectionReceived += OnSocketConnectionReceived; await _listenerSocket.BindEndpointAsync(EndpointPairs[0].LocalHostName, Globals.strServerPort); rootPage.NotifyUserFromBackground("Devices connected on L2, listening on IP Address: " + EndpointPairs[0].LocalHostName.ToString() + " Port: " + Globals.strServerPort, NotifyType.StatusMessage); } else { // Decline the connection request rootPage.NotifyUserFromBackground("Connection request from " + connectionRequest.DeviceInformation.Name + " was declined", NotifyType.ErrorMessage); connectionRequest.Dispose(); } } catch (Exception ex) { rootPage.NotifyUserFromBackground("Connect operation threw an exception: " + ex.Message, NotifyType.ErrorMessage); } }
private async void StartListener_Click(object sender, RoutedEventArgs e) { if (CoreApplication.Properties.ContainsKey("listener")) { rootPage.NotifyUser("此步骤完成,请下一步", NotifyType.ErrorMessage); return; } if (String.IsNullOrEmpty(ServiceNameForListener.Text)) { rootPage.NotifyUser("请输入服务器名", NotifyType.ErrorMessage); } CoreApplication.Properties.Remove("serverAddress"); CoreApplication.Properties.Remove("adapter"); LocalHostItem selectedLocalHost = null; if((BindToAddress.IsChecked == true) || (BindToAdapter.IsChecked == true)) { selectedLocalHost = (LocalHostItem)AdapterList.SelectedItem; if (selectedLocalHost == null) { rootPage.NotifyUser("请选择ip", NotifyType.ErrorMessage); return; } CoreApplication.Properties.Add("servereAddress", selectedLocalHost.LoacalHost.CanonicalName); } StreamSocketListener listener = new StreamSocketListener(); listener.ConnectionReceived += OnConnection; listener.Control.KeepAlive = false; //保存socket,便于以后使用 CoreApplication.Properties.Add("listener", listener); //开始监听操作 try { if (BindToAny.IsChecked == true) { await listener.BindServiceNameAsync(ServiceNameForListener.Text); rootPage.NotifyUser("Listening", NotifyType.StatusMessage); } else if (BindToAddress.IsChecked == true) { await listener.BindEndpointAsync(selectedLocalHost.LoacalHost, ServiceNameForListener.Text); rootPage.NotifyUser("Listening on address" + selectedLocalHost.LoacalHost.CanonicalName, NotifyType.StatusMessage); } else if (BindToAdapter.IsChecked == true) { // Try to limit traffic to the selected adapter. //尝试与所选适配器有限通讯 // This option will be overridden by interfaces with weak-host or forwarding modes enabled. NetworkAdapter selectedAdapter = selectedLocalHost.LoacalHost.IPInformation.NetworkAdapter; CoreApplication.Properties.Add("adapter", selectedAdapter); await listener.BindServiceNameAsync(ServiceNameForListener.Text, SocketProtectionLevel.PlainSocket, selectedAdapter); rootPage.NotifyUser("Listening on adapter " + selectedAdapter.NetworkAdapterId, NotifyType.StatusMessage); } } catch (Exception exception) { CoreApplication.Properties.Remove("listener"); if (SocketError.GetStatus(exception.HResult) == SocketErrorStatus.Unknown) { throw; } rootPage.NotifyUser("开启监听失败: " + exception.Message, NotifyType.ErrorMessage); } }
private async Task<bool> HandleConnectionRequestAsync(WiFiDirectConnectionRequest connectionRequest) { string deviceName = connectionRequest.DeviceInformation.Name; bool isPaired = (connectionRequest.DeviceInformation.Pairing?.IsPaired == true) || (await IsAepPairedAsync(connectionRequest.DeviceInformation.Id)); // Show the prompt only in case of WiFiDirect reconnection or Legacy client connection. if (isPaired || _publisher.Advertisement.LegacySettings.IsEnabled) { var messageDialog = new MessageDialog($"Connection request received from {deviceName}", "Connection Request"); // Add two commands, distinguished by their tag. // The default command is "Decline", and if the user cancels, we treat it as "Decline". messageDialog.Commands.Add(new UICommand("Accept", null, true)); messageDialog.Commands.Add(new UICommand("Decline", null, null)); messageDialog.DefaultCommandIndex = 1; messageDialog.CancelCommandIndex = 1; // Show the message dialog var commandChosen = await messageDialog.ShowAsync(); if (commandChosen.Id == null) { return false; } } 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; var listenerSocket = new StreamSocketListener(); // Save this (listenerSocket, wfdDevice) pair so we can hook it up when the socket connection is made. _pendingConnections[listenerSocket] = wfdDevice; var 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; }
public async void AddStreamSocketListenerAsync(UInt16 port) { ThrowIfDisposed(); manager.NotifyUser("Adding stream socket listener for TCP port " + port, NotifyType.StatusMessage); var endpointPairCollection = session.GetConnectionEndpointPairs(); // Create listener for socket connection (and add to list to cleanup later) StreamSocketListener listenerSocket = new StreamSocketListener(); StreamSocketListenerWrapper listenerWrapper = new StreamSocketListenerWrapper( manager, listenerSocket, this ); streamSocketListeners.Add(listenerWrapper); manager.NotifyUser("BindEndpointAsync...", NotifyType.StatusMessage); await listenerSocket.BindEndpointAsync(endpointPairCollection[0].LocalHostName, Convert.ToString(port, CultureInfo.InvariantCulture)); manager.NotifyUser("BindEndpointAsync Done", NotifyType.StatusMessage); manager.NotifyUser("AddStreamSocketListenerAsync...", NotifyType.StatusMessage); await session.AddStreamSocketListenerAsync(listenerSocket); manager.NotifyUser("AddStreamSocketListenerAsync Done", NotifyType.StatusMessage); }
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; } }
// 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; }