/// <summary> /// Gets accurate time using the NTP protocol with default timeout of 45 seconds. /// </summary> /// <param name="timeout">Operation timeout.</param> /// <returns>Network accurate <see cref="DateTime"/> value.</returns> public async Task<DateTime> GetNetworkTimeAsync(TimeSpan timeout) { using (var socket = new DatagramSocket()) using (var ct = new CancellationTokenSource(timeout)) { ct.Token.Register(() => _resultCompletionSource.TrySetCanceled()); socket.MessageReceived += OnSocketMessageReceived; //The UDP port number assigned to NTP is 123 await socket.ConnectAsync(new HostName("pool.ntp.org"), "123"); using (var writer = new DataWriter(socket.OutputStream)) { // NTP message size is 16 bytes of the digest (RFC 2030) var ntpBuffer = new byte[48]; // Setting the Leap Indicator, // Version Number and Mode values // LI = 0 (no warning) // VN = 3 (IPv4 only) // Mode = 3 (Client Mode) ntpBuffer[0] = 0x1B; writer.WriteBytes(ntpBuffer); await writer.StoreAsync(); var result = await _resultCompletionSource.Task; return result; } } }
private async void btnConnect_Click(object sender, RoutedEventArgs e) { Windows.Networking.Sockets.DatagramSocket socket = new Windows.Networking.Sockets.DatagramSocket(); socket.MessageReceived += Socket_MessageReceived; //You can use any port that is not currently in use already on the machine. We will be using two separate and random //ports for the client and server because both the will be running on the same machine. string serverPort = "8001"; string clientPort = "8002"; //Because we will be running the client and server on the same machine, we will use localhost as the hostname. Windows.Networking.HostName serverHost = new Windows.Networking.HostName("127.0.0.1"); //Bind the socket to the clientPort so that we can start listening for UDP messages from the UDP echo server. await socket.BindServiceNameAsync(clientPort); await socket.ConnectAsync(serverHost, serverPort); //Write a message to the UDP echo server. Stream streamOut = (await socket.GetOutputStreamAsync(serverHost, serverPort)).AsStreamForWrite(); StreamWriter writer = new StreamWriter(streamOut); string message = "I'm the message from client!"; await writer.WriteLineAsync(message); await writer.FlushAsync(); }
public override async void Start() { if (_Started) return; _SequenceNumber = 1; try { // Connect to the Drone udpClient = new DatagramSocket(); await udpClient.BindServiceNameAsync(_ServiceName); await udpClient.ConnectAsync(new HostName(DroneClient.Host), _ServiceName); udpWriter = new DataWriter(udpClient.OutputStream); udpWriter.WriteByte(1); await udpWriter.StoreAsync(); _Timer = ThreadPoolTimer.CreatePeriodicTimer(new TimerElapsedHandler(timerElapsedHandler), TimeSpan.FromMilliseconds(25)); _Started = true; } catch (Exception) { Stop(); } }
private async void ConnectSocket_Click(object sender, RoutedEventArgs e) { if (string.IsNullOrEmpty(ServiceNameForConnect.Text)) { _rootPage.NotifyUser("Please provide a service name.", NotifyType.ErrorMessage); return; } HostName hostName; try { hostName = new HostName(HostNameForConnect.Text); } catch (ArgumentException) { _rootPage.NotifyUser("Error: Invalid host name.", NotifyType.ErrorMessage); return; } if (CoreApplication.Properties.ContainsKey("clientSocket")) { _rootPage.NotifyUser("This step has already been executed. Please move to the next one.", NotifyType.ErrorMessage); return; } // クライアントソケットの作成 var socket = new Windows.Networking.Sockets.DatagramSocket(); if (DontFragment.IsOn) { // IPフラグメンテーションを許可しない socket.Control.DontFragment = true; } socket.MessageReceived += MessageReceived; CoreApplication.Properties.Add("clientSocket", socket); _rootPage.NotifyUser("Connecting to: " + HostNameForConnect.Text, NotifyType.StatusMessage); try { // サーバソケットに接続しにいく await socket.ConnectAsync(hostName, ServiceNameForConnect.Text); _rootPage.NotifyUser("Connected", NotifyType.StatusMessage); CoreApplication.Properties.Add("connected", null); } catch (Exception exception) { if (SocketError.GetStatus(exception.HResult) == SocketErrorStatus.Unknown) { throw; } _rootPage.NotifyUser("Connect failed with error: " + exception.Message, NotifyType.ErrorMessage); } }
public void Start() { _socket = new DatagramSocket(); _socket.Control.DontFragment = true; _socket.ConnectAsync(new HostName("255.255.255.255"), "19227").AsTask().Wait(); _outputStream = _socket.OutputStream.AsStreamForWrite(); _timer.Change(0, Timeout.Infinite); }
private async Task SendResponseAsync(HostName target, DiscoveryResponse response) { var buffer = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(response)); using (var socket = new DatagramSocket()) { await socket.ConnectAsync(target, DEFAULT_PORT.ToString()); await socket.OutputStream.WriteAsync(buffer.AsBuffer()); await socket.OutputStream.FlushAsync(); } }
public async void ConnectedToServer() { // 资料来自 http://www.devdiv.com/forum.php?mod=viewthread&tid=134558 //创建一个本地连接 udpSocket = new DatagramSocket(); //创建新的hostName HostName remoteHost = new HostName("168.63.151.29"); //打开一个至远程主机的连接,后面是远程端口号。。 await udpSocket.ConnectAsync(remoteHost, "3000"); }
public async Task<bool> StartupAsync(string serverIP, int serverPort) { await ShutdownAsync(); IsRunning = true; messageReceiptAwaiters = new Stack<TaskCompletionSource<byte[]>>(); socket = new DatagramSocket(); socket.MessageReceived += socket_MessageReceived; await socket.ConnectAsync(new HostName(serverIP), serverPort.ToString()); return true; }
public override async void Start() { udpClient = new DatagramSocket(); // Connect To Drone udpClient.MessageReceived += MessageReceived; await udpClient.BindServiceNameAsync(_ServiceName); await udpClient.ConnectAsync(new HostName(DroneClient.Host), _ServiceName); udpWriter = new DataWriter(udpClient.OutputStream); SendKeepAliveSignal(); _TimeoutStopWatch = Stopwatch.StartNew(); }
public static async void SynchronizeDeviceTime() { DatagramSocket socket = new DatagramSocket(); socket.MessageReceived += DatagramSocket_MessageReceived; await socket.ConnectAsync(new HostName("time.windows.com"), "123"); using (DataWriter writer = new DataWriter(socket.OutputStream)) { byte[] container = new byte[48]; container[0] = 0x1B; writer.WriteBytes(container); await writer.StoreAsync(); } }
/// <summary> /// 在此页将要在 Frame 中显示时进行调用。 /// </summary> /// <param name="e">描述如何访问此页的事件数据。Parameter /// 属性通常用于配置页。</param> async protected override void OnNavigatedTo(NavigationEventArgs e) { // 创建一个新的socket实例,并绑定到一个本地端口上 DatagramSocket udpSocket = new DatagramSocket(); await udpSocket.BindServiceNameAsync("3721"); // 打开一个连接到远程主机上 HostName remoteHost = new HostName("192.168.1.100"); await udpSocket.ConnectAsync(remoteHost, "3721"); // 将一个字符串以UDP数据包形式发送到远程主机上 DataWriter udpWriter = new DataWriter(udpSocket.OutputStream); udpWriter.WriteString("这里是破船之家"); await udpWriter.StoreAsync(); }
/// <summary> /// connect to server /// </summary> /// <param name="_host">target ip address</param> /// <param name="_axisPort">axis channel port</param> /// <param name="_ctlPort">control channel port</param> /// <param name="_trackPort">track channel port</param> /// <returns></returns> public async Task connect(string _host,int _axisPort,int _ctlPort, int _trackPort) { host = _host; trackPort = _trackPort; AxisBuffer = new byte[AxisMsgSize]; CtlBuffer = new byte[CtlMsgSize]; trackBuffer = new byte[trackMsgSize]; //connecting var localSettings = Windows.Storage.ApplicationData.Current.LocalSettings; axisSocket = new DatagramSocket(); ctlSocket = new DatagramSocket(); trackSocket = new DatagramSocket(); HostName hostname = new HostName(host); await axisSocket.ConnectAsync(hostname, _axisPort.ToString()); await ctlSocket.ConnectAsync(hostname, _ctlPort.ToString()); await trackSocket.ConnectAsync(hostname, trackPort.ToString()); connected = true; }
async partial void SendTimeRequest() { var socket = new Windows.Networking.Sockets.DatagramSocket(); AsyncUdpResult asyncResult = null; try { var buffer = new byte[48]; buffer[0] = 0x1B; socket.MessageReceived += Socket_Completed_Receive; asyncResult = new AsyncUdpResult(socket); await socket.ConnectAsync(new Windows.Networking.HostName(_ServerAddress), "123").AsTask().ConfigureAwait(false); using (var udpWriter = new DataWriter(socket.OutputStream)) { udpWriter.WriteBytes(buffer); await udpWriter.StoreAsync().AsTask().ConfigureAwait(false); udpWriter.WriteBytes(buffer); await udpWriter.StoreAsync().AsTask().ConfigureAwait(false); asyncResult.Wait(OneSecond); } } catch (Exception ex) { try { if (socket != null) { ExecuteWithSuppressedExceptions(() => socket.MessageReceived -= this.Socket_Completed_Receive); ExecuteWithSuppressedExceptions(() => socket.Dispose()); } } finally { OnErrorOccurred(ExceptionToNtpNetworkException(ex)); } } finally { asyncResult?.Dispose(); } }
public static async Task WakeAsync(HostName endPoint, int port, byte[] macAddress) { var packet = new List<byte>(); for (var i = 0; i < 6; i++) // Trailer of 6 FF packets packet.Add(0xFF); for (var i = 0; i < 16; i++) // Repeat 16 times the MAC address packet.AddRange(macAddress); using (var socket = new DatagramSocket()) { await socket.ConnectAsync(endPoint, port.ToString()); var stream = socket.OutputStream; using (var writer = new DataWriter(stream)) { writer.WriteBytes(packet.ToArray()); await writer.StoreAsync(); } } }
public async void Locate() { DatagramSocket socket = new DatagramSocket(); //socket.Control.DontFragment = true; socket.MessageReceived += MessageReceived; try { //// Connect to the server (in our case the listener we created in previous step). await socket.ConnectAsync(new HostName("255.255.255.255"), "8888"); //await socket.ConnectAsync(new HostName("192.168.1.177"), "8888"); //rootPage.NotifyUser("Connected", NotifyType.StatusMessage); // Mark the socket as connected. Set the value to null, as we care only about the fact that the property is set. //CoreApplication.Properties.Add("connected", null); DataWriter udpWriter = new DataWriter(socket.OutputStream); udpWriter.WriteString("SNC"); await udpWriter.StoreAsync(); //byte[] msg = new byte[] { 35, 36, 37 }; //IOutputStream stream = await socket.GetOutputStreamAsync(new HostName("255.255.255.255"), "8888"); //await stream.WriteAsync(BytesToBuffer(msg)); } 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; } //rootPage.NotifyUser("Connect failed with error: " + exception.Message, NotifyType.ErrorMessage); } }
public override async void Start() { if (_Started) return; _SequenceNumber = 1; // Connect To Drone udpClient = new DatagramSocket(); await udpClient.BindServiceNameAsync(_ServiceName); await udpClient.ConnectAsync(new HostName(DroneClient.Host), _ServiceName); udpWriter = new DataWriter(udpClient.OutputStream); //string path = string.Format("AR.Drone-CommandHistory_{0:yyyy-MM-dd-HH-mm}.txt", DateTime.Now); //commandHistoryFile = await ApplicationData.Current.TemporaryFolder.CreateFileAsync(path, CreationCollisionOption.ReplaceExisting); // Write first message //byte[] firstMessage = BitConverter.GetBytes(1); //WriteString(firstMessage.ToString()); udpWriter.WriteByte(1); await udpWriter.StoreAsync(); _Timer = ThreadPoolTimer.CreatePeriodicTimer(new TimerElapsedHandler(timerElapsedHandler), TimeSpan.FromMilliseconds(25)); _Started = true; }
private async Task SendIdentifierToDevice(HostName remoteAddress) { using (var socket = new DatagramSocket()) { await socket.ConnectAsync(remoteAddress, Settings.RemoteServiceName); using (var dataStream = socket.OutputStream.AsStreamForWrite()) { var identifier = DeviceRegistration.Current.DeviceIdentifier.ToString(); var data = Encoding.UTF8.GetBytes(string.Format(CultureInfo.InvariantCulture, "{0}:{1}", Protocol.TickTack.SendDeviceInfoCommand, identifier)); dataStream.Write(data, 0, data.Length); await dataStream.FlushAsync(); Log($"TACK sent to {remoteAddress} - device identifier: {identifier}"); } } }
/// <summary> /// Connects the client to a given remote address and port. /// </summary> async public void Connect() { if(_udpClient != null) Close(); _udpClient = new DatagramSocket(); writer = new DataWriter(_udpClient.OutputStream); try { HostName hn = new HostName(_ipAddress); await _udpClient.ConnectAsync(hn,_port); } catch { throw new Exception(String.Format("Can't create client at IP address {0} and port {1}.", _ipAddress,_port)); } }
/// <summary> /// This is the click handler for the 'ConnectSocket' button. /// </summary> /// <param name="sender">Object for which the event was generated.</param> /// <param name="e">Event's parameters.</param> private async void ConnectSocket_Click(object sender, RoutedEventArgs e) { if (String.IsNullOrEmpty(ServiceNameForConnect.Text)) { rootPage.NotifyUser("Please provide a service name.", NotifyType.ErrorMessage); return; } // By default 'HostNameForConnect' is disabled and host name validation is not required. When enabling the // text box validating the host name is required since it was received from an untrusted source (user // input). The host name is validated by catching ArgumentExceptions thrown by the HostName constructor for // invalid input. HostName hostName; try { hostName = new HostName(HostNameForConnect.Text); } catch (ArgumentException) { rootPage.NotifyUser("Error: Invalid host name.", NotifyType.ErrorMessage); return; } if (CoreApplication.Properties.ContainsKey("clientSocket")) { rootPage.NotifyUser( "This step has already been executed. Please move to the next one.", NotifyType.ErrorMessage); return; } DatagramSocket socket = new DatagramSocket(); if (DontFragment.IsOn) { // Set the IP DF (Don't Fragment) flag. // This won't have any effect when running both client and server on localhost. // Refer to the DatagramSocketControl class' MSDN documentation for the full list of control options. socket.Control.DontFragment = true; } socket.MessageReceived += MessageReceived; // Save the socket, so subsequent steps can use it. CoreApplication.Properties.Add("clientSocket", socket); rootPage.NotifyUser("Connecting to: " + HostNameForConnect.Text, NotifyType.StatusMessage); try { // Connect to the server (by default, the listener we created in the previous step). await socket.ConnectAsync(hostName, ServiceNameForConnect.Text); rootPage.NotifyUser("Connected", NotifyType.StatusMessage); // Mark the socket as connected. Set the value to null, as we care only about the fact that the // property is set. CoreApplication.Properties.Add("connected", null); } 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; } rootPage.NotifyUser("Connect failed with error: " + exception.Message, NotifyType.ErrorMessage); } }
public async static void ConnectedToServer() { // 资料来自 http://www.devdiv.com/forum.php?mod=viewthread&tid=134558 //创建一个本地连接 udpSocket = new DatagramSocket(); //绑定本地端口,服务器想要接收消息应该在这个端口。。 await udpSocket.BindServiceNameAsync("5556"); //创建新的hostName HostName remoteHost = new HostName("192.168.1.1"); //打开一个至远程主机的连接,后面是远程端口号。。 await udpSocket.ConnectAsync(remoteHost, "5556"); }
// // UDP send. // private async void UdpSend_Click_1(object sender, RoutedEventArgs e) { DatagramSocket sendSocket = new DatagramSocket(); // Even when we do not except any response, this handler is called if any error occurrs. sendSocket.MessageReceived += OnMessageReceived; try { await sendSocket.ConnectAsync(new HostName("foohost"), "2704"); // DatagramSocket.ConnectAsync() vs DatagramSocket.GetOutputStreamAsync()? // Use DatagramSocket.GetOutputStreamAsync() if datagrams are sent to multiple // GetOutputStreamAsync() does DNS resolution first. // If remote host does not exist, "No such host is known. (Exception from HRESULT: 0x80072AF9)" // exception is thrown. // If remote host is not listening on the specified host, "An existing connection was forcibly // closed by the remote host. (Exception from HRESULT: 0x80072746)" exception is thrown. string message = "¡Hello, I am the new guy in the network!"; DataWriter writer = new DataWriter(sendSocket.OutputStream); // This is useless in this sample. Just a friendly remainder. uint messageLength = writer.MeasureString(message); writer.WriteString(message); uint bytesWritten = await writer.StoreAsync(); Debug.Assert(bytesWritten == messageLength); DisplayOutput(UdpSendOutput, "Message sent: " + message); } catch (Exception ex) { DisplayOutput(UdpSendOutput, ex.ToString()); } }
private async void received_Click(object sender, RoutedEventArgs e) { DatagramSocket datagramSocket = new DatagramSocket(); datagramSocket.MessageReceived+=datagramSocket_MessageReceived2; await datagramSocket.ConnectAsync(new HostName("localhost"), "22112"); }
/// <summary> /// Gets the current date and time from the specified /// NTP server. /// </summary> /// <param name="server">Specifies the host name or IP address /// of the NTP server to call.</param> /// <returns>Returns a DateTime instance containing the date and time /// obtained from the NTP server.</returns> public async Task<DateTimeOffset?> GetAsync(string server) { DateTimeOffset? returnValue = null; // *** // *** Create a DatagramSocket for the UDP message // *** DatagramSocket socket = new DatagramSocket(); // *** // *** // *** ManualResetEvent _clientDone = new ManualResetEvent(false); // *** // *** Connect the callback for the response data // *** socket.MessageReceived += (s, a) => { DataReader reader = a.GetDataReader(); byte[] data = new byte[48]; reader.ReadBytes(data); returnValue = this.ConvertDateTime(data); // *** // *** Signal that the callback is complete // *** _clientDone.Set(); }; // *** // *** Get the host name instance and connect // *** the socket. // *** HostName serverHost = new HostName(server); await socket.ConnectAsync(serverHost, PORT); // *** // *** Get a data writer for the network stream // *** DataWriter dataWriter = new DataWriter(socket.OutputStream); // *** // *** RFC 2030 // *** byte[] ntpData = new byte[48]; ntpData[0] = 0x1B; dataWriter.WriteBytes(ntpData); // *** // *** Send the data // *** uint result = await dataWriter.StoreAsync(); // *** // *** Wait for the callback to complete // *** if (!_clientDone.WaitOne(this.Timeout)) { throw new TimeoutException(); } return returnValue; }
// This will fire when the connected peer attempts to open a port for this connection // The peer should start a stream socket listener (for TCP) private async void OnRemotePortAdded(WiFiDirectServiceSession sender, WiFiDirectServiceRemotePortAddedEventArgs args) { try { ThrowIfDisposed(); var endpointPairCollection = args.EndpointPairs; var protocol = args.Protocol; if (endpointPairCollection.Count == 0) { manager.NotifyUser("No endpoint pairs for remote port added event", NotifyType.ErrorMessage); return; } manager.NotifyUser(String.Format("{0} Port {1} Added by remote peer", (protocol == WiFiDirectServiceIPProtocol.Tcp) ? "TCP" : ((protocol == WiFiDirectServiceIPProtocol.Udp) ? "UDP" : "???"), endpointPairCollection[0].RemoteServiceName ), NotifyType.StatusMessage ); SocketWrapper socketWrapper = null; if (args.Protocol == WiFiDirectServiceIPProtocol.Tcp) { // Connect to the stream socket listener StreamSocket streamSocket = new StreamSocket(); socketWrapper = new SocketWrapper(manager, streamSocket, null); manager.NotifyUser("Connecting to stream socket...", NotifyType.StatusMessage); await streamSocket.ConnectAsync(endpointPairCollection[0]); // Start receiving messages recursively var rcv = socketWrapper.ReceiveMessageAsync(); manager.NotifyUser("Stream socket connected", NotifyType.StatusMessage); } else if (args.Protocol == WiFiDirectServiceIPProtocol.Udp) { // Connect a socket over UDP DatagramSocket datagramSocket = new DatagramSocket(); socketWrapper = new SocketWrapper(manager, null, datagramSocket); manager.NotifyUser("Connecting to datagram socket...", NotifyType.StatusMessage); await datagramSocket.ConnectAsync(endpointPairCollection[0]); manager.NotifyUser("Datagram socket connected", NotifyType.StatusMessage); } else { manager.NotifyUser("Bad protocol for remote port added event", NotifyType.ErrorMessage); return; } socketList.Add(socketWrapper); // Update manager so UI can add to list manager.AddSocket(socketWrapper); } catch (Exception ex) { manager.NotifyUser("OnRemotePortAdded Failed: " + ex.Message, NotifyType.ErrorMessage); } }
private async void ConnectToOSC_Click(object sender, RoutedEventArgs e) { socket = new DatagramSocket(); socket.MessageReceived += RecieveOSC; await socket.ConnectAsync(new HostName(host.Text),port.Text); writer = new DataWriter(socket.OutputStream); }
/// <summary> /// 连接Udp服务 /// </summary> private async void connectButton_Click(object sender, RoutedEventArgs e) { hostName = new HostName(hostIP.Text); DatagramSocket socket = new DatagramSocket(); CoreApplication.Properties.Add("clientSocket", socket); try { await socket.ConnectAsync(hostName, hostPort.Text); CoreApplication.Properties.Add("connected", null); } catch (Exception ee) { } finally { connectButton.IsEnabled = false; _accelerometer = Accelerometer.GetDefault(); if (_accelerometer != null) { // Select a report interval that is both suitable for the purposes of the app and supported by the sensor. // This value will be used later to activate the sensor. // send(); //} uint minReportInterval = _accelerometer.MinimumReportInterval; _desiredReportInterval = minReportInterval > 16 ? minReportInterval : 16; _accelerometer.ReportInterval = _desiredReportInterval; _accelerometer.ReadingChanged += new TypedEventHandler<Accelerometer, AccelerometerReadingChangedEventArgs>(ReadingChanged); readyToSend(); } else { readyToSend(); MessageDialog msg = new MessageDialog("No accelerometer found"); msg.ShowAsync(); } } }