public IPAddress(uint value) { m_addressBytes = IPAddressHelper.GetAddressBytes(value); m_value = value; m_stringValue = IPAddressHelper.GetAddressString(m_addressBytes); m_hostName = new HostName(m_stringValue); }
/// <summary> /// Attempt a TCP socket connection to the given host over the given port /// </summary> /// <param name="serverAddress">The address of the server</param> /// <param name="portNumber">The port number to connect</param> private bool Connect(string serverAddress, int portNumber) { HostName serverHost = new HostName(serverAddress); mSocket = new StreamSocket(); mSocket.Control.KeepAlive = true; Task connectTask = mSocket.ConnectAsync(serverHost, portNumber.ToString()).AsTask(); try { if(!connectTask.Wait(TIMEOUT)) { // timed out connecting to the server System.Diagnostics.Debug.WriteLine("Timed out connecting to TCP server"); return false; } } catch(AggregateException a) { // exception when running connect task. failed to connect to server System.Diagnostics.Debug.WriteLine("Failed to connect to TCP server. Error: " + a.GetBaseException().Message); return false; } // set up the writer writer = new DataWriter(mSocket.OutputStream); // set up the reader reader = new DataReader(mSocket.InputStream); reader.InputStreamOptions = InputStreamOptions.Partial; // Set inputstream options so that we don't have to know the data size // start listening for messages Task.Run(() => StartReceiving()); // start receiving on a new thread Task.Run(() => StartKeepAlive()); // start receiving on a new thread return true; }
private async void ConnectUWP(string host, string port) #endif { #if UNITY_EDITOR StatusTextManager.GetComponent <TextMesh>().text = "UWP TCP client used in Unity!"; #else try { if (exchangeTask != null) { StopExchange(); } socket = new Windows.Networking.Sockets.StreamSocket(); Windows.Networking.HostName serverHost = new Windows.Networking.HostName(host); await socket.ConnectAsync(serverHost, port); Stream streamOut = socket.OutputStream.AsStreamForWrite(); writer = new StreamWriter(streamOut) { AutoFlush = true }; Stream streamIn = socket.InputStream.AsStreamForRead(); reader = new StreamReader(streamIn); RestartExchange(); StatusTextManager.GetComponent <TextMesh>().text = "Connected!"; } catch (Exception e) { errorStatus = e.ToString(); } #endif }
public async void DoesAThing() { var hostName = new HostName("stun.l.google.com"); var port = 19302; var taskCompletionSource = new TaskCompletionSource<StunUri>(); using (var datagramSocket = new DatagramSocket()) { datagramSocket.MessageReceived += async (sender, e) => { var buffer = await e.GetDataStream().ReadAsync(null, 100, InputStreamOptions.None).AsTask(); var stunMessage = StunMessage.Parse(buffer.ToArray()); var xorMappedAddressStunMessageAttribute = stunMessage.Attributes.OfType<XorMappedAddressStunMessageAttribute>().Single(); taskCompletionSource.SetResult(new StunUri(xorMappedAddressStunMessageAttribute.HostName, xorMappedAddressStunMessageAttribute.Port)); }; using (var inMemoryRandomAccessStream = new InMemoryRandomAccessStream()) { var stunMessageId = new StunMessageId(CryptographicBuffer.GenerateRandom(12).ToArray()); var stunMessageType = StunMessageType.BindingRequest; var stunMessageAttributes = new StunMessageAttribute[] { }; var stunMessage = new StunMessage(stunMessageType, stunMessageAttributes, stunMessageId); var bytes = stunMessage.ToLittleEndianByteArray(); var outputStream = await datagramSocket.GetOutputStreamAsync(hostName, $"{port}"); var written = await outputStream.WriteAsync(bytes.AsBuffer()); } } var result = await taskCompletionSource.Task; Assert.AreEqual(result.HostName, new HostName("200.100.50.25")); Assert.AreEqual(result.Port, 12345); }
public FrameUploader(string id, IPAddress address, int port) { _host = new HostName(address.ToString()); _port = port.ToString(); _cameraId = id; UploadComplete = () => { }; }
/// <summary> /// Creates a new instance of SmtpSocket. /// </summary> /// <param name="server">Server host name.</param> /// <param name="port">Port (usually 25).</param> /// <param name="ssl">SSL/TLS support.</param> public SmtpSocket(string server, int port, bool ssl) { _host = new HostName(server); _socket = new StreamSocket(); _port = port; _ssl = ssl; }
private async Task ConnectAsyncInternal(HostName hostName) { _tokenSource = new CancellationTokenSource(); _socket = new StreamSocket(); // połącz z kontrolerem na porcie 5555 await _socket.ConnectAsync(hostName, "5555", SocketProtectionLevel.PlainSocket); // wyslij komendę odblokowującą await _socket.OutputStream.WriteAsync(Encoding.UTF8.GetBytes(UnlockCommand).AsBuffer()); // read the "Accept:EV340\r\n\r\n" response //stworzenie bufor na odpowiedź IBuffer bufferResponse = new Buffer(128); //pobranie do bufora odpowiedzi przychodzącej od kontrolera EV3 await _socket.InputStream.ReadAsync(bufferResponse, bufferResponse.Capacity, InputStreamOptions.Partial); //przekształcenie danych z bufora na ciag znaków w formacie UTF8 string response = Encoding.UTF8.GetString(bufferResponse.ToArray(), 0, (int)bufferResponse.Length); if (string.IsNullOrEmpty(response)) //zgłoszenie błędu w razie braku odpowiedzi throw new Exception("LEGO EV3 brick did not respond to the unlock command."); //rozpoczęcie pobierania danych await ThreadPool.RunAsync(PollInput); }
private void ProcessDeviceDiscoveryMessage(HostName remoteAddress, string remotePort, LifxResponse msg) { if (DiscoveredBulbs.ContainsKey(remoteAddress.ToString())) //already discovered { DiscoveredBulbs[remoteAddress.ToString()].LastSeen = DateTime.UtcNow; //Update datestamp return; } if (msg.Source != discoverSourceID || //did we request the discovery? _DiscoverCancellationSource == null || _DiscoverCancellationSource.IsCancellationRequested) //did we cancel discovery? return; var device = new LightBulb() { HostName = remoteAddress, Service = msg.Payload[0], Port = BitConverter.ToUInt32(msg.Payload, 1), LastSeen = DateTime.UtcNow }; DiscoveredBulbs[remoteAddress.ToString()] = device; devices.Add(device); if (DeviceDiscovered != null) { DeviceDiscovered(this, new DeviceDiscoveryEventArgs() { Device = device }); } }
/// <summary> /// Checks if remote is reachable. RT apps cannot do loopback so this will alway return false. /// You can use it to check remote calls though. /// </summary> /// <param name="host"></param> /// <param name="msTimeout"></param> /// <returns></returns> public override async Task<bool> IsReachable(string host, int msTimeout = 5000) { if (string.IsNullOrEmpty(host)) throw new ArgumentNullException("host"); if (!IsConnected) return false; try { var serverHost = new HostName(host); using(var client = new StreamSocket()) { await client.ConnectAsync(serverHost, "http"); return true; } } catch(Exception ex) { Debug.WriteLine("Unable to reach: " + host + " Error: " + ex); return false; } }
private void ConnectUWP(string host, string port) #endif { #if UNITY_EDITOR errorStatus = "UWP TCP client used in Unity!"; #else try { socket = new Windows.Networking.Sockets.StreamSocket(); Windows.Networking.HostName serverHost = new Windows.Networking.HostName(host); socket.ConnectAsync(serverHost, port); Stream streamOut = socket.OutputStream.AsStreamForWrite(); writer = new StreamWriter(streamOut) { AutoFlush = true }; Stream streamIn = socket.InputStream.AsStreamForRead(); reader = new StreamReader(streamIn); Debug.Log("success connected to" + host); } catch (Exception e) { errorStatus = e.ToString(); Debug.Log("Error could not connect to" + host); isConnected = false; return; } #endif isConnected = true; }
private async void ConnectUWP(string host, string port) { try { if (exchangeTask != null) { StopExchange(); } socket = new Windows.Networking.Sockets.StreamSocket(); Windows.Networking.HostName serverHost = new Windows.Networking.HostName(host); await socket.ConnectAsync(serverHost, port); Stream streamOut = socket.OutputStream.AsStreamForWrite(); writer = new StreamWriter(streamOut) { AutoFlush = true }; Stream streamIn = socket.InputStream.AsStreamForRead(); reader = new StreamReader(streamIn); } catch (Exception e) { e.ToString(); } }
//Connects to server public async Task connect(string address, int port) { if (!this.connected) { try { this.socket = new StreamSocket(); this.hostname = new HostName(address); this.port = port; await this.socket.ConnectAsync(this.hostname, port.ToString()); this.writer = new DataWriter(this.socket.OutputStream); this.reader = new DataReader(this.socket.InputStream); this.reader.InputStreamOptions = InputStreamOptions.Partial; connected = true; } catch (Exception e) { connected = false; Debug.WriteLine(e.Message); } } else { await new MessageDialog("Already connected", "Information").ShowAsync(); connected = true; } }
public Settings() { socket = new StreamSocket(); ConnectToServer(); host = new HostName("192.168.12.171"); this.InitializeComponent(); }
private async void ConnectSocket_Click(object sender, RoutedEventArgs e) { if (string.IsNullOrEmpty(ServiceNameForConnect.Text)) { rootPage.NotifyUser("请提供服务器名", NotifyType.ErrorMessage); return; } HostName hostName; try { hostName = new HostName(HostNameForConnect.Text); } catch (ArgumentException) { rootPage.NotifyUser("错误:无效主机名", NotifyType.ErrorMessage); return; } rootPage.NotifyUser("连接至" + HostNameForConnect.Text, NotifyType.StatusMessage); using (StreamSocket socket = new StreamSocket()) { socket.Control.ClientCertificate = null; bool shouldRetry = await TryConnectSocketWithRetryAsync(socket, hostName); if (shouldRetry) { await TryConnectSocketWithRetryAsync(socket, hostName); } } }
public void connect(string args) { string[] javascriptArgs = JsonHelper.Deserialize<string[]>(args); string macAddress = javascriptArgs[0]; connectionCallbackId = javascriptArgs[1]; connectionManager = new ConnectionManager(); connectionManager.Initialize(); // TODO can't we put this in the constructor? connectionManager.ByteReceived += connectionManager_ByteReceived; connectionManager.ConnectionSuccess += connectionManager_ConnectionSuccess; connectionManager.ConnectionFailure += connectionManager_ConnectionFailure; try { HostName deviceHostName = new HostName(macAddress); connectionManager.Connect(deviceHostName); } catch (Exception ex) { Debug.WriteLine(ex); connectionManager_ConnectionFailure("Invalid Hostname"); } }
private async void ConnectUWP() { try { if (exchangeTask != null) { CloseSocket(); } socket = new Windows.Networking.Sockets.StreamSocket(); Windows.Networking.HostName serverHost = new Windows.Networking.HostName(host); await socket.ConnectAsync(serverHost, port); Stream streamOut = socket.OutputStream.AsStreamForWrite(); writer = new StreamWriter(streamOut) { AutoFlush = true }; Stream streamIn = socket.InputStream.AsStreamForRead(); reader = new StreamReader(streamIn); RestartExchange(); connected = true; } catch (Exception e) { Debug.Log("ERROR WHILE TRYING TO CONNECT: " + e.ToString()); } }
/// <summary> /// Initialize the connection to the network (prepare sockets, join multicast group, handle the right events, etc) /// </summary> /// <returns></returns> public void InitializeSockets() { if (Initialized) return; MulticastAddress = new HostName(MulticastAddressStr); // To receive packets (either unicast or multicast), a MessageReceived event handler must be defined // Initialize the multicast socket and register the event MulticastSocket = new DatagramSocket(); MulticastSocket.MessageReceived += MulticastSocketMessageReceived; // bind to a local UDP port MulticastSocket.BindServiceNameAsync(MulticastPortStr).AsTask().Wait(); // Call the JoinMulticastGroup method to join the multicast group. MulticastSocket.JoinMulticastGroup(MulticastAddress); // Get our IP address String MyIPString = PeerConnector.GetMyIP(); myIPAddress = new HostName(MyIPString); // Construct a list of ip addresses that should be ignored IgnoreableNetworkAddresses = new List<String> { LinkLocalPrefixString, LocalLoopbackPrefixString, PrivateNetworkPrefixString }; //, MyIPString }; System.Diagnostics.Debug.WriteLine("Ignored IP Addresses: " + LinkLocalPrefixString + " - " + LocalLoopbackPrefixString + " - " + PrivateNetworkPrefixString); TCPListener = new TCPSocketListener("80085", new TCPRequestHandler(ProcessNetworkObject)); TCPSocketHelper = new TCPSocketClient("80085"); TCPListener.Start(); Initialized = true; }
public static async void init(TiSettings settings) { if (!settings.ContainsKey("logToken") || settings["logToken"].Length == 0) { return; } logToken = settings["logToken"]; multicastSocket = new DatagramSocket(); multicastSocket.MessageReceived += multicastSocket_MessageReceived; HostName hostname = new HostName("239.6.6.6"); try { await multicastSocket.BindServiceNameAsync("8666"); multicastSocket.JoinMulticastGroup(hostname); IOutputStream stream = await multicastSocket.GetOutputStreamAsync(hostname, "8666"); DataWriter writer = new DataWriter(stream); writer.WriteString("TI_WP8_LOGGER"); await writer.StoreAsync(); writer.DetachStream(); stream.Dispose(); } catch (Exception ex) { if (SocketError.GetStatus(ex.HResult) == SocketErrorStatus.Unknown) { throw; } Debug.WriteLine(ex.ToString()); } }
private void RemoveRoutePolicy_Click(object sender, RoutedEventArgs e) { if (rootPage.g_ConnectionSession == null) { OutputText.Text = "Please establish a connection using the \"Create Connection\" scenario first."; return; } try { HostName hostName = new HostName(HostName.Text); DomainNameType domainNameType = ParseDomainNameType(((ComboBoxItem)DomainNameTypeComboBox.SelectedItem).Content.ToString()); RoutePolicy routePolicy = new RoutePolicy(rootPage.g_ConnectionSession.ConnectionProfile, hostName, domainNameType); Windows.Networking.Connectivity.ConnectivityManager.RemoveHttpRoutePolicy(routePolicy); OutputText.Text = "Removed Route Policy\nTraffic to " + routePolicy.HostName.ToString() + " will no longer be routed through " + routePolicy.ConnectionProfile.ProfileName; } catch (ArgumentException ex) { OutputText.Text = "Failed to remove Route Policy with HostName = \"" + HostName.Text + "\"\n" + ex.Message; } }
public async void sendMessage(string message) { Debug.Log("LearningHub.sendMessage 1: IP: " + IPAddress + ", port: " + port + ", message: " + message); #if !UNITY_EDITOR try { // Create the StreamSocket using (var streamSocket = new Windows.Networking.Sockets.StreamSocket()) { // The server hostname that we will be establishing a connection to. In this example, the server and client are in the same process. var hostName = new Windows.Networking.HostName(IPAddress); Debug.Log("LearningHub.sendMessage 2: Host: " + hostName + ", IP: " + IPAddress + ", port: " + port + ", message: " + message); await streamSocket.ConnectAsync(hostName, port); using (Stream outputStream = streamSocket.OutputStream.AsStreamForWrite()) { using (var streamWriter = new StreamWriter(outputStream)) { await streamWriter.WriteLineAsync(message); await streamWriter.FlushAsync(); } } Debug.Log("LearningHub.sendMessage 3: Host: " + hostName + ", IP: " + IPAddress + ", port: " + port + ", message: " + message); } } catch (Exception ex) { Windows.Networking.Sockets.SocketErrorStatus webErrorStatus = Windows.Networking.Sockets.SocketError.GetStatus(ex.GetBaseException().HResult); Debug.Log("Learning hub not found"); } #endif Debug.Log("WEKIT LearningHUb: sending message to learning hub"); }
/// <summary> /// Used to send SSDP packet /// </summary> /// <param name="data">The SSDP packet</param> /// <returns>unused</returns> public async Task<int> Send(string data) { socket = new DatagramSocketWrapper(); var profile = NetworkInformation.GetInternetConnectionProfile(); socket.MessageReceived += (sender, args) => { HandleDatagramMessage(args); }; try { socket.BindServiceNameAsync("", profile.NetworkAdapter); } catch (Exception e) { Logger.Current.AddMessage("There was an error binding the multicast socket: " + e.Message); } var remoteHost = new HostName(SSDP.Address); var reqBuff = Encoding.UTF8.GetBytes(data); var stream = await socket.GetOutputStreamAsync(remoteHost, SSDP.Port.ToString()); await stream.WriteAsync(reqBuff.AsBuffer()); if (IsConnected) return 0; socket.JoinMulticastGroup(remoteHost); IsConnected = !IsConnected; return 0; }
public static void Connect(string address, string port) { if (!connected) { clientSocket = new StreamSocket(); try { serverHost = new HostName(address); serverPort = port; serverHostnameString = address; writer = new DataWriter(clientSocket.OutputStream); clientSocket.ConnectAsync(serverHost, serverPort); connected = true; } catch (Exception) { clientSocket.Dispose(); clientSocket = null; throw new ConnectionErrorException(); } } else { clientSocket.Dispose(); clientSocket = null; connected = false; GamepadClient.Connect(address, port); } }
public async void SendMessage(string msg) { HostName hostName; try { hostName = new HostName("localhost"); } catch (ArgumentException) { return; } StreamSocket socket; try { using (socket = new StreamSocket()) { await socket.ConnectAsync(hostName, port2); //CoreApplication.Properties.Add("connected", null); DataWriter dw = new DataWriter(socket.OutputStream); dw.WriteString(msg); await dw.StoreAsync(); } } catch { //break; } }
internal async Task ConnectAsync( HostName hostName, string serviceName, string user, string password) { if (controlStreamSocket != null) { throw new InvalidOperationException("Control connection already started."); } this.hostName = hostName; controlStreamSocket = new StreamSocket(); await controlStreamSocket.ConnectAsync(hostName, serviceName); reader = new DataReader(controlStreamSocket.InputStream); reader.InputStreamOptions = InputStreamOptions.Partial; writer = new DataWriter(controlStreamSocket.OutputStream); readCommands = new List<string>(); loadCompleteEvent = new AutoResetEvent(false); readTask = InfiniteReadAsync(); FtpResponse response; response = await GetResponseAsync(); VerifyResponse(response, 220); response = await UserAsync(user); VerifyResponse(response, 331); response = await PassAsync(password); VerifyResponse(response, 230); }
override public async Task ConnectAsync(DeviceInfo RacerDevice) { try { //First connect to the bluetooth device... HostName deviceHost = new HostName(RacerDevice.HostName); //If the socket is already in use, dispose of it if (streamSocket != null || dataWriter != null) CloseConnection(); //Create a new socket streamSocket = new StreamSocket(); await streamSocket.ConnectAsync(deviceHost, "1"); dataWriter = new DataWriter(streamSocket.OutputStream); RaisePropertyChanged("IsConnected"); } catch(Exception ex) { //Dispose and Destroy the StreamSocket and DataWriter CloseConnection(); //Not sure what to do here yet, just pass it along throw; } finally { //Regardless of what happened, let the view know that the connection state likely changed. RaiseRacerConnectionStateChanged(); } }
private async void Init() { _Listener = new DatagramSocket(); _Listener.MessageReceived += Listener_MessageReceived; while (true) { try { await _Listener.BindServiceNameAsync("6"); break; } catch (COMException) { var messageDialog = new MessageDialog("Only one usage of each port is normally permitted.\r\n\r\nIs 'Windows IoT Core Watcher' open?", "Port in use"); messageDialog.Commands.Add(new UICommand("Try again", (command) => { })); await messageDialog.ShowAsync(); } } HostName hostname = new HostName("239.0.0.222"); _Listener.JoinMulticastGroup(hostname); _Settings = ApplicationData.Current.LocalSettings; _Timer = new Timer(Timer_Callback, null, 1000, 1000); }
public async void ConnectAsync(string ipOrHost, int port, SocketEventArgs args) { _socket = new StreamSocket(); var server = new HostName(ipOrHost); // TCP timeouts in WinRT are excessive, shorten them here using task cancellation var cts = new CancellationTokenSource(); try { cts.CancelAfter(MqttProtocolInformation.Settings.NetworkTimeout * 1000); _logger.LogMessage("Socket", LogLevel.Verbose, string.Format("Authenticating client certificate with remote host CN={0}", server.CanonicalName)); await _socket.ConnectAsync(server, port.ToString(), GetSocketProtectionLevel(args.EncryptionLevel)).AsTask(cts.Token); _clientUid = args.ClientUid; StartReceiving(); } catch (TaskCanceledException) { args.SocketException = new IOException("Timeout error while trying to connect."); _clientUid = null; _socket.Dispose(); _socket = null; } catch (Exception ex) { args.SocketException = ex; _clientUid = null; _socket.Dispose(); _socket = null; } args.Complete(); }
public async Task<bool> Connect() { if (_connected) return false; var hostname = new HostName("62.4.24.188"); //var hostname = new HostName("192.168.1.12"); CancellationTokenSource cts = new CancellationTokenSource(); try { cts.CancelAfter(5000); await _clientSocket.ConnectAsync(hostname, "4242").AsTask(cts.Token); } catch (TaskCanceledException) { _connected = false; return false; } _connected = true; _dataReader = new DataReader(_clientSocket.InputStream) { InputStreamOptions = InputStreamOptions.Partial }; ReadData(); return true; }
public KnxController(HostName hostName, int port, string password = "") { if (hostName == null) throw new ArgumentNullException(nameof(hostName)); _hostName = hostName; _port = port; _password = password; }
public Connection(string hostname, int port) { m_HostName = new HostName(hostname); m_Port = port; m_Sender = new Sender(); m_ServerConnectionState = ServerConnectionState.Disconnected; }
private async void OnForegroundSocketClicked(object sender, RoutedEventArgs e) { socket = new StreamSocket(); HostName host = new HostName("localhost"); try { await socket.ConnectAsync(host, "1983"); isConnected = true; while (isConnected) { try { DataReader reader; using (reader = new DataReader(socket.InputStream)) { // Set the DataReader to only wait for available data (so that we don't have to know the data size) reader.InputStreamOptions = InputStreamOptions.Partial; // The encoding and byte order need to match the settings of the writer we previously used. reader.UnicodeEncoding = UnicodeEncoding.Utf8; reader.ByteOrder = ByteOrder.LittleEndian; // Send the contents of the writer to the backing stream. // Get the size of the buffer that has not been read. await reader.LoadAsync(256); // Keep reading until we consume the complete stream. while (reader.UnconsumedBufferLength > 0) { string readString = reader.ReadString(reader.UnconsumedBufferLength); await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { messages.Add(readString); }); Debug.WriteLine(readString); await reader.LoadAsync(256); } reader.DetachStream(); } } catch (Exception exc) { MessageDialog dialog = new MessageDialog("Error reading the data"); await dialog.ShowAsync(); } } } catch (Exception exc) { MessageDialog dialog = new MessageDialog("Error connecting to the socket"); await dialog.ShowAsync(); } }
private async void Button_Click(object sender, RoutedEventArgs e) { HostName targetHost; try { targetHost = new HostName(HostnameBox.Text); } catch(ArgumentException ex) { MessageDialog errorDialog = new MessageDialog("You've entered an invalid hostname or IP address.\nNote that the hostname field should not contain port numbers."); errorDialog.Title = "Invalid Hostname or IP address"; await errorDialog.ShowAsync(); return; } uint port = Convert.ToUInt32(PortNumberBox.Text); string macAddress = MacAddressBox.Text; MagicPacketSender magicSender = new MagicPacketSender(); bool success = await magicSender.SendMagicPacket(targetHost, port, macAddress); RequestInfo info = new RequestInfo ( HostnameBox.Text, Convert.ToUInt32(PortNumberBox.Text), MacAddressBox.Text ); if (!RecentRequests.Contains(info)) { if (RecentRequests.Count > 20) { for (int i = 20; i <= RecentRequests.Count; i++) { RecentRequests.RemoveAt(i); } } RecentRequests.Insert(0, info); await FileUtils.SaveRequestInfo(RecentRequests.ToList()); } if (success) { ToastPrompt toast = new ToastPrompt(); toast.Title = "Magic Packet"; toast.Message = " Magic packet sent!"; toast.TextOrientation = Orientation.Horizontal; toast.MillisecondsUntilHidden = 3000; toast.Show(); } else { ToastPrompt toast = new ToastPrompt(); toast.Title = "Magic Packet"; toast.Message = " Sending failed! =("; toast.TextOrientation = Orientation.Horizontal; toast.MillisecondsUntilHidden = 3000; toast.Show(); } }
public Networking() { _socket = new StreamSocket(); _localHost = new HostName("192.168.1.113"); _remoteHost = new HostName("192.168.1.145"); _serviceName = "1337"; _endpointpair = new EndpointPair(_localHost, _serviceName, _remoteHost, _serviceName); }
/// <summary> /// Sets the endpoint at the specified address/port pair as the 'default' target of sent data. /// After calling <code>ConnectAsync</code>, use <code>SendAsync</code> to send data to the default target. /// </summary> /// <param name="address">The remote address for the default target.</param> /// <param name="port">The remote port for the default target.</param> public Task ConnectAsync(string address, int port) { var hn = new HostName(address); var sn = port.ToString(); return _backingDatagramSocket .ConnectAsync(hn, sn) .WrapNativeSocketExceptionsAsTask(); }
// Use this for initialization void Start() { string message = "Hello :)"; #if NETFX_CORE HostAddress = new Windows.Networking.HostName("192.168.43.41"); SendMessage(message); #endif }
/// <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); }
public static async void setup(Spritesheet sp) { animationLibrary = sp; socket = new Windows.Networking.Sockets.StreamSocket(); HostName hostname = new Windows.Networking.HostName("192.168.137.1"); await socket.ConnectAsync(hostname, "87776"); reader = new Windows.Storage.Streams.DataReader(socket.InputStream); writer = new Windows.Storage.Streams.DataWriter(socket.OutputStream); messageQueue.ForEach(sendMessage); startServerRead(); }
private async void StartClient() { try { // Create the StreamSocket and establish a connection to the echo server. using (var streamSocket = new Windows.Networking.Sockets.StreamSocket()) { // The server hostname that we will be establishing a connection to. In this example, the server and client are in the same process. var hostName = new Windows.Networking.HostName("localhost"); this.clientListBox.Items.Add("client is trying to connect..."); await streamSocket.ConnectAsync(hostName, StreamSocketAndListenerPage.PortNumber); this.clientListBox.Items.Add("client connected"); // Send a request to the echo server. string request = "Hello, World!"; using (Stream outputStream = streamSocket.OutputStream.AsStreamForWrite()) { using (var streamWriter = new StreamWriter(outputStream)) { await streamWriter.WriteLineAsync(request); await streamWriter.FlushAsync(); } } this.clientListBox.Items.Add(string.Format("client sent the request: \"{0}\"", request)); // Read data from the echo server. string response; using (Stream inputStream = streamSocket.InputStream.AsStreamForRead()) { using (StreamReader streamReader = new StreamReader(inputStream)) { response = await streamReader.ReadLineAsync(); } } this.clientListBox.Items.Add(string.Format("client received the response: \"{0}\" ", response)); } this.clientListBox.Items.Add("client closed its socket"); } catch (Exception ex) { Windows.Networking.Sockets.SocketErrorStatus webErrorStatus = Windows.Networking.Sockets.SocketError.GetStatus(ex.GetBaseException().HResult); this.clientListBox.Items.Add(webErrorStatus.ToString() != "Unknown" ? webErrorStatus.ToString() : ex.Message); } }
public async Task <string> sendMessage(string message, bool awaitResponse) { Debug.Log("sending message to learning hub: " + message); string responseMessage = ""; #if !UNITY_EDITOR try { // Create the StreamSocket using (Windows.Networking.Sockets.StreamSocket streamSocket = new Windows.Networking.Sockets.StreamSocket()) { // The server hostname that we will be establishing a connection to. In this example, the server and client are in the same process. var hostName = new Windows.Networking.HostName(IPAddress); await streamSocket.ConnectAsync(hostName, port); using (Stream outputStream = streamSocket.OutputStream.AsStreamForWrite()) { using (StreamWriter streamWriter = new StreamWriter(outputStream)) { await streamWriter.WriteLineAsync(message); await streamWriter.FlushAsync(); } } if (awaitResponse) { using (Stream inputStream = streamSocket.InputStream.AsStreamForRead()) { using (StreamReader streamReader = new StreamReader(inputStream)) { responseMessage = streamReader.ReadToEnd(); } } } } } catch (Exception ex) { Windows.Networking.Sockets.SocketErrorStatus webErrorStatus = Windows.Networking.Sockets.SocketError.GetStatus(ex.GetBaseException().HResult); } #endif Debug.Log("sent message to learning hub: " + message); if (awaitResponse) { Debug.Log("received response from learning hub: " + responseMessage); } return(responseMessage); }
async Task ConnectAsync(string host, string port) { try { #if !UNITY_EDITOR ClientSocket = new Windows.Networking.Sockets.StreamSocket(); Windows.Networking.HostName serverHost = new Windows.Networking.HostName(host); await ClientSocket.ConnectAsync(serverHost, port); #endif } catch (Exception e) { client.NotifyMainThread(0, e.ToString(), 0); } }
/// <summary> /// established a TCP socket connection to receive packets from another device. /// This is used when running as a UWP app on the HoloLens. /// </summary> private async void ConnectSocketUWP() { try { socket = new Windows.Networking.Sockets.StreamSocket(); Windows.Networking.HostName serverHost = new Windows.Networking.HostName(ipAddress); await socket.ConnectAsync(serverHost, portUWP); Stream streamIn = socket.InputStream.AsStreamForRead(); reader = new StreamReader(streamIn, Encoding.UTF8); connection = true; } catch (Exception e) { //do something } }
public async System.Threading.Tasks.Task <string> Connect(string ip_addr, string port) { connectSocket = new Windows.Networking.Sockets.StreamSocket(); Windows.Networking.HostName serverHost = new Windows.Networking.HostName(ip_addr); try { await connectSocket.ConnectAsync(serverHost, port); } catch { _canConnect = false; _connected = false; throw new Exception("Server not found."); } streamOut = connectSocket.OutputStream.AsStreamForWrite(); streamIn = connectSocket.InputStream.AsStreamForRead(); writer = new StreamWriter(streamOut); reader = new StreamReader(streamIn); _connected = true; return(null); }
public static IPAddress GetInternetIP() { // http://stackoverflow.com/questions/10336521/query-local-ip-address var icp = NetworkInformation.GetInternetConnectionProfile(); if (icp?.NetworkAdapter == null) { return(null); } Windows.Networking.HostName hostname = NetworkInformation.GetHostNames() .SingleOrDefault( hn => hn.IPInformation?.NetworkAdapter != null && hn.IPInformation.NetworkAdapter.NetworkAdapterId == icp.NetworkAdapter.NetworkAdapterId); // the ip address return(IPAddress.Parse(hostname?.CanonicalName)); }
private async Task <bool> ConnectSocketAsync() { //setup the connection via socket ipAddress = IPAddress.Parse("192.168.0.10"); //hard coded in obdlink MX port = 35000; //hard coded in obdlink MX ipEndPoint = new IPEndPoint(ipAddress, port); socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); var hostName = new Windows.Networking.HostName("192.168.0.10"); await streamSocket.ConnectAsync(hostName, port.ToString()); using (streamSocket = new Windows.Networking.Sockets.StreamSocket()) { stream = streamSocket.InputStream.AsStreamForRead(); connected = true; } return(true); }
private async void ConnectUWP(string host, string port) #endif { #if UNITY_EDITOR Debug.Log("Can't use UWP TCP client in Unity!"); #else try { socket = new Windows.Networking.Sockets.StreamSocket(); Windows.Networking.HostName serverHost = new Windows.Networking.HostName(host); await socket.ConnectAsync(serverHost, port); stream = socket.InputStream.AsStreamForRead(); Initialize(); Debug.Log("Connected!"); } catch (Exception e) { Debug.Log(e.ToString()); } #endif }
private async void ConnectUWP(string host, string port) #endif { #if UNITY_EDITOR errorStatus = "UWP TCP client used in Unity!"; #else try { socket = new Windows.Networking.Sockets.StreamSocket(); Windows.Networking.HostName serverHost = new Windows.Networking.HostName(host); await socket.ConnectAsync(serverHost, port); streamIn = socket.InputStream.AsStreamForRead(); } catch (Exception e) { errorStatus = e.ToString(); } #endif }
IEnumerator StartConnection() { LOGWARNING("Really trying to connect"); #if !UNITY_EDITOR && (UNITY_WSA || NETFX_CORE) Loom.RunAsync(async() => #else Loom.RunAsync(() => #endif { while (!stopCommunication) { LOGWARNING("Connecting to receiver ..."); #if !UNITY_EDITOR && (UNITY_WSA || NETFX_CORE) HostName receiverHostName = new Windows.Networking.HostName(receiverIPAddress); await receiverSocket.ConnectAsync(receiverHostName, receiverPort.ToString()); Stream streamIn = receiverSocket.InputStream.AsStreamForRead(); Stream streamOut = receiverSocket.OutputStream.AsStreamForWrite(); binReader = new BinaryReader(streamIn); binWriter = new BinaryWriter(streamOut); #else receiverClient.Connect(IPAddress.Parse(receiverIPAddress), receiverPort); receiverClientStream = receiverClient.GetStream(); binReader = new BinaryReader(receiverClientStream); binWriter = new BinaryWriter(receiverClientStream); #endif LOGWARNING("Connected with receiver"); isConnected = true; } }); while (!isConnected) { Debug.Log("I am here " + instanceNumber); yield return(null); } // Start receiving data as well ReceiveData(); }
private async void ConnectUWP(string host, string port) #endif { #if UNITY_EDITOR Debug.Log("UWP TCP client used in Unity!"); #else try { socket = new Windows.Networking.Sockets.StreamSocket(); Windows.Networking.HostName serverHost = new Windows.Networking.HostName(host); await socket.ConnectAsync(serverHost, port); stream = socket.InputStream.AsStreamForRead(); #if !UNITY_EDITOR exchangeTask = Task.Run(() => Read_Data()); #endif Debug.Log("Connected!"); } catch (Exception e) { Debug.Log(e.ToString()); } #endif }
public static async Task StartClient() { try { // Create the StreamSocket and establish a connection to the echo server. streamSocket = new Windows.Networking.Sockets.StreamSocket(); // The server hostname that we will be establishing a connection to. In this example, the server and client are in the same process. var hostName = new Windows.Networking.HostName("192.168.0.137"); MainPage.MP.clientListBox.Items.Add("client is trying to connect..."); await streamSocket.ConnectAsync(hostName, "1234"); MainPage.MP.clientListBox.Items.Add("client connected"); } catch (Exception ex) { Windows.Networking.Sockets.SocketErrorStatus webErrorStatus = Windows.Networking.Sockets.SocketError.GetStatus(ex.GetBaseException().HResult); MainPage.MP.clientListBox.Items.Add(webErrorStatus.ToString() != "Unknown" ? webErrorStatus.ToString() : ex.Message); } }
private Task <T> BroadcastMessageAsync <T>(Windows.Networking.HostName hostName, FrameHeader header, MessageType type, params object[] args) where T : LifxResponse { List <byte> payload = new List <byte>(); if (args != null) { foreach (var arg in args) { if (arg is UInt16) { payload.AddRange(BitConverter.GetBytes((UInt16)arg)); } else if (arg is UInt32) { payload.AddRange(BitConverter.GetBytes((UInt32)arg)); } else if (arg is byte) { payload.Add((byte)arg); } else if (arg is byte[]) { payload.AddRange((byte[])arg); } else if (arg is string) { payload.AddRange(Encoding.UTF8.GetBytes(((string)arg).PadRight(32).Take(32).ToArray())); //All strings are 32 bytes } else { throw new NotSupportedException(args.GetType().FullName); } } } return(BroadcastMessagePayloadAsync <T>(hostName, header, type, payload.ToArray())); }
private async void DoSomeShit() { try { // Create the StreamSocket and establish a connection to the echo server. using (var streamSocket = new StreamSocket()) { // The server hostname that we will be establishing a connection to. In this example, the server and client are in the same process. var hostName = new Windows.Networking.HostName("1.1.1.1"); this.clientListBox.Items.Add("client is trying to connect..."); await streamSocket.ConnectAsync(hostName, "853", SocketProtectionLevel.Tls12); IBuffer certificateBuffer = streamSocket.Information.ServerCertificate.GetCertificateBlob(); Stream certificateStream = certificateBuffer.AsStream(); //Take the SHA2-256 hash of the DER ASN.1 encoded value Byte[] digest; using (var sha2 = new SHA256Managed()) { digest = sha2.ComputeHash(certificateStream); } //Convert hash to base64 String hash = Convert.ToBase64String(digest); this.clientListBox.Items.Add("client connected"); } this.clientListBox.Items.Add("client closed its socket"); } catch (Exception ex) { Windows.Networking.Sockets.SocketErrorStatus webErrorStatus = Windows.Networking.Sockets.SocketError.GetStatus(ex.GetBaseException().HResult); this.clientListBox.Items.Add(webErrorStatus.ToString() != "Unknown" ? webErrorStatus.ToString() : ex.Message); } }
//private string serverAdress = "127.0.0.1"; private async Task <TaskResult> SetupClient() { try { //Create the StreamSocket and establish a connection to the echo server. socket = new Windows.Networking.Sockets.StreamSocket(); //The server hostname that we will be establishing a connection to. We will be running the server and client locally, //so we will use localhost as the hostname. Windows.Networking.HostName serverHost = new Windows.Networking.HostName(serverAdress); //Every protocol typically has a standard port number. For example HTTP is typically 80, FTP is 20 and 21, etc. //For the echo server/client application we will use a random port 1337. string serverPort = "6670"; await socket.ConnectAsync(serverHost, serverPort); } catch (Exception e) { return(new TaskResult(false, e.Message)); } return(new TaskResult(true, "OK")); }
//This one is used to make a connection #else private async void ConnectUWP(string host, int port) { try { //Connect using streamSockets socket = new Windows.Networking.Sockets.StreamSocket(); Windows.Networking.HostName serverHost = new Windows.Networking.HostName(host); await socket.ConnectAsync(serverHost, port.ToString()); //Set up asynchronous reading Stream streamIn = socket.InputStream.AsStreamForRead(); reader = new StreamReader(streamIn); //Make thread to read lines exchangeTask = Task.Run(() => DoReadUwp()); Debug.Log("Connected! uwp"); } catch (Exception e) { Debug.Log("uwp: " + e.ToString()); } }
/// <summary> /// Starts a Proxy that takes local DNS requests and transforms them into /// DNS-over-TLS versions instead, using the provided DNS-over-TLS endpoint. /// </summary> private async void StartDNSToDNSOverTLSProxy() { try { var serverDatagramSocket = new DatagramSocket(); // The ConnectionReceived event is raised when connections are received. serverDatagramSocket.MessageReceived += ServerDatagramSocket_MessageReceived; this.serverListBox.Items.Add("server is about to bind..."); var hostName = new Windows.Networking.HostName("192.168.175.13"); // Start listening for incoming TCP connections on the specified port. You can specify any port that's not currently in use. //await serverDatagramSocket.BindEndpointAsync(hostName, DNS_LISTENING_PORT); await serverDatagramSocket.BindServiceNameAsync(DNS_LISTENING_PORT); this.serverListBox.Items.Add(string.Format("server is bound to port number {0}", DNS_LISTENING_PORT)); } catch (Exception ex) { Windows.Networking.Sockets.SocketErrorStatus webErrorStatus = Windows.Networking.Sockets.SocketError.GetStatus(ex.GetBaseException().HResult); this.serverListBox.Items.Add(webErrorStatus.ToString() != "Unknown" ? webErrorStatus.ToString() : ex.Message); } }
private async void initSockets(string host, int inputPort, int outputPort) { // input socket inputSocket = new DatagramSocket(); Windows.Networking.HostName serverAddr = new Windows.Networking.HostName(host); Stream streamOut = (await inputSocket.GetOutputStreamAsync(serverAddr, "" + inputPort)).AsStreamForWrite(); inputWriter = new StreamWriter(streamOut); // output socket outputSocket = new DatagramSocket(); outputSocket.MessageReceived += Socket_MessageReceived; try { await outputSocket.BindServiceNameAsync("" + outputPort); } catch (Exception e) { Debug.Log(e.ToString()); Debug.Log(Windows.Networking.Sockets.SocketError.GetStatus(e.HResult).ToString()); return; } }
/// <summary> /// Attempts to send a magic packet to the desination hostname, on the specified port with the specified MAC address. /// </summary> /// <param name="destination">Destination hostname or IP address.</param> /// <param name="destinationPort">Destination port number.</param> /// <param name="targetMac">Destination MAC address. Bytes can be separated by colons, dashes, or nothing.</param> /// <returns>True if magic packet is sent successfully, false otherwise.</returns> public async Task <bool> SendMagicPacket(Windows.Networking.HostName destination, uint destinationPort, string targetMac) { try { DatagramSocket _socket = new DatagramSocket(); using (var stream = await _socket.GetOutputStreamAsync(destination, destinationPort.ToString())) { //Split on common MAC separators char?splitChar = null; if (targetMac.Contains('-')) { splitChar = '-'; } else if (targetMac.Contains(':')) { splitChar = ':'; } else if (targetMac.Contains(' ')) { splitChar = ' '; } //Turn MAC into array of bytes byte[] macAsArray; if (splitChar != null) { macAsArray = targetMac.Split((char)splitChar) .Select(b => Convert.ToByte(b, 16)) .ToArray <byte>(); } else { //Jump through MAC-string, reading 2 chars at a time macAsArray = Enumerable.Range(0, targetMac.Length) .Where(x => x % 2 == 0) .Select(x => Convert.ToByte(targetMac.Substring(x, 2), 16)) //16 = hexadecimal .ToArray(); } List <byte> magicPacket = new List <byte> { 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF }; //A WoLAN magic packet is just FF FF FF FF FF FF, then the target MAC adress repeated 16 times. for (int i = 0; i < 16; i++) { magicPacket = magicPacket.Concat(macAsArray).ToList(); } using (DataWriter writer = new DataWriter(stream)) { writer.WriteBytes(magicPacket.ToArray <byte>()); await writer.StoreAsync(); await writer.FlushAsync(); return(true); } } } catch (Exception e) { Debug.WriteLine(e); return(false); } }
private async Task <T> BroadcastMessagePayloadAsync <T>(Windows.Networking.HostName hostName, FrameHeader header, MessageType type, byte[] payload) where T : LifxResponse { #if DEBUG MemoryStream ms = new MemoryStream(); await WritePacketToStreamAsync(ms.AsOutputStream(), header, (UInt16)type, payload).ConfigureAwait(false); var data = ms.ToArray(); System.Diagnostics.Debug.WriteLine( string.Join(",", (from a in data select a.ToString("X2")).ToArray())); #endif if (hostName == null) { hostName = new Windows.Networking.HostName("255.255.255.255"); } TaskCompletionSource <T> tcs = null; if (//header.AcknowledgeRequired && header.Identifier > 0 && typeof(T) != typeof(UnknownResponse)) { tcs = new TaskCompletionSource <T>(); Action <LifxResponse> action = (r) => { if (!tcs.Task.IsCompleted) { if (r.GetType() == typeof(T)) { tcs.SetResult((T)r); } else { } } }; taskCompletions[header.Identifier] = action; } using (var stream = await _socket.GetOutputStreamAsync(hostName, Port)) { await WritePacketToStreamAsync(stream, header, (UInt16)type, payload).ConfigureAwait(false); } T result = default(T); if (tcs != null) { var _ = Task.Delay(1000).ContinueWith((t) => { if (!t.IsCompleted) { tcs.TrySetException(new TimeoutException()); } }); try { result = await tcs.Task.ConfigureAwait(false); } finally { taskCompletions.Remove(header.Identifier); } } return(result); }