private async void StartClient() { try { // Create the DatagramSocket and establish a connection to the echo server. var clientDatagramSocket = new Windows.Networking.Sockets.DatagramSocket(); clientDatagramSocket.MessageReceived += ClientDatagramSocket_MessageReceived; // 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"); await clientDatagramSocket.BindServiceNameAsync("servername"); // Send a request to the echo server. string request = "Hello, World!"; using (var serverDatagramSocket = new Windows.Networking.Sockets.DatagramSocket()) { using (Stream outputStream = (await serverDatagramSocket.GetOutputStreamAsync(hostName, "3655")).AsStreamForWrite()) { using (var streamWriter = new StreamWriter(outputStream)) { //await streamWriter.WriteAsync(); await streamWriter.FlushAsync(); } } } } catch (Exception ex) { Windows.Networking.Sockets.SocketErrorStatus webErrorStatus = Windows.Networking.Sockets.SocketError.GetStatus(ex.GetBaseException().HResult); } }
public static async Task StartCommand() { // WORK AS CLIENT try { client = new Windows.Networking.Sockets.DatagramSocket(); client.MessageReceived += ClientDatagramSocket_MessageReceived; //var hostName = new HostName(TelloIpAddress); await client.BindServiceNameAsync(CommandPortNumber); // await client.ConnectAsync(new HostName(TelloIpAddress), CommandPortNumber); var a = client.Information; // Init, and set the speed to the minimum await SendCommand("command"); await SendCommand("speed 10"); // await SendCommand("streamon"); IsCommandReady = true; } catch (Exception ex) { Windows.Networking.Sockets.SocketErrorStatus webErrorStatus = Windows.Networking.Sockets.SocketError.GetStatus(ex.GetBaseException().HResult); Debug.WriteLine(webErrorStatus.ToString() != "Unknown" ? webErrorStatus.ToString() : ex.Message); } }
private async void ServerDatagramSocket_MessageReceived(Windows.Networking.Sockets.DatagramSocket sender, Windows.Networking.Sockets.DatagramSocketMessageReceivedEventArgs args) { string request; using (DataReader dataReader = args.GetDataReader()) { request = dataReader.ReadString(dataReader.UnconsumedBufferLength).Trim(); } await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => listbox_Logger.Items.Add(request)); // Echo the request back as the response. using (Stream outputStream = (await sender.GetOutputStreamAsync(args.RemoteAddress, "1337")).AsStreamForWrite()) { using (var streamWriter = new StreamWriter(outputStream)) { await streamWriter.WriteLineAsync(request); await streamWriter.FlushAsync(); } } //await this.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => this.listbox_Logger.Items.Add(string.Format("server sent back the response: \"{0}\"", request))); sender.Dispose(); // await this.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => this.listbox_Logger.Items.Add("server closed its socket")); }
private static void Current_MessageReceived(Windows.Networking.Sockets.DatagramSocket sender, MessageModel message) { UDPServer.Current.MessageReceived -= Current_MessageReceived; try { switch (message.Type) { case MessageType.WiFiConnect: using (DataReader dataReader = DataReader.FromBuffer(message.Content)) { dataReader.UnicodeEncoding = Windows.Storage.Streams.UnicodeEncoding.Utf8; string str = dataReader.ReadString(message.ContentLength); string[] s = str.Split('@'); string ssid = s[0]; string password = s[1]; ConnectWlan(ssid, password); resetEvent.Set(); //To-Do: 发送消息告诉客户端连接结果 } break; } } catch (Exception ex) { throw ex; } }
private async void Socket_MessageReceived(Windows.Networking.Sockets.DatagramSocket sender, Windows.Networking.Sockets.DatagramSocketMessageReceivedEventArgs e) { Stream streamIn = e.GetDataStream().AsStreamForRead(); StreamReader streamReader = new StreamReader(streamIn); string message = await streamReader.ReadLineAsync(); string[] tokens = message.Split(','); // Handle Message if (message[0] == 't' && tokens.Length == 12) { string percentString = "0 : " + tokens[2] + "\n" + "1 : " + tokens[3] + "\n" + "2 : " + tokens[4] + "\n" + "3 : " + tokens[5] + "\n" + "4 : " + tokens[6] + "\n" + "5 : " + tokens[7] + "\n" + "6 : " + tokens[8] + "\n" + "7 : " + tokens[9] + "\n" + "8 : " + tokens[10] + "\n" + "9 : " + tokens[11] + "\n"; await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () => { //UI code here resultText.Text = tokens[1]; percentText.Text = percentString; }); } }
public AutoDetectUDPClient(MonoBehaviour behaviour, int port, int targetPortMin, int targetPortMax, float pingInterval, string additionalInformation) { this.behaviour = behaviour; this.pingInterval = pingInterval; #if NETFX_CORE this.Client = new Windows.Networking.Sockets.DatagramSocket(); this.Client.BindServiceNameAsync(port.ToString()).AsTask().Wait(); #else this.Client = new UdpClient(port); this.Client.EnableBroadcast = true; #endif this.BroadcastEndPoint = new IPEndPoint[targetPortMax - targetPortMin + 1]; for (int i = 0; i < this.BroadcastEndPoint.Length; i++) #if UNITY_WSA_8_1 || UNITY_WP_8_1 { this.BroadcastEndPoint[i] = new IPEndPoint(); this.BroadcastEndPoint[i].Port = targetPortMin + i; } #else { this.BroadcastEndPoint[i] = new IPEndPoint(IPAddress.Broadcast, targetPortMin + i); } #endif this.SetAdditionalInformation(additionalInformation); this.pingCoroutine = this.behaviour.StartCoroutine(this.AsyncSendPing()); }
private void Socket_MessageReceived(Windows.Networking.Sockets.DatagramSocket sender, Windows.Networking.Sockets.DatagramSocketMessageReceivedEventArgs args) { using (var reader = args.GetDataReader()) { var buf = new byte[reader.UnconsumedBufferLength]; reader.ReadBytes(buf); MessageReceived?.Invoke(new DatagramSocketMessage(args.RemoteAddress.CanonicalName, buf)); } }
private async void Socket_MessageReceived(Windows.Networking.Sockets.DatagramSocket sender, Windows.Networking.Sockets.DatagramSocketMessageReceivedEventArgs args) { //Read the message that was received from the UDP echo client. Stream streamIn = args.GetDataStream().AsStreamForRead(); StreamReader reader = new StreamReader(streamIn); message = await reader.ReadLineAsync(); //Create a new socket to send the same message back to the UDP echo client. }
private void HandlerWithLambaExample() { Windows.Networking.Sockets.DatagramSocket socket = new Windows.Networking.Sockets.DatagramSocket(); socket.MessageReceived += new TypedEventHandler < Windows.Networking.Sockets.DatagramSocket, Windows.Networking.Sockets.DatagramSocketMessageReceivedEventArgs>((datagramSocket, eventArgs) => { // Empty handler. }); }
public override void StopServer() { #if NETFX_CORE this.client.Dispose(); #else this.client.Close(); #endif this.client = null; InternalNGDebug.LogFile("Stopped UDPListener."); }
private void ClientDatagramSocket_MessageReceived(Windows.Networking.Sockets.DatagramSocket sender, Windows.Networking.Sockets.DatagramSocketMessageReceivedEventArgs args) { string response; using (DataReader dataReader = args.GetDataReader()) { response = dataReader.ReadString(dataReader.UnconsumedBufferLength).Trim(); } sender.Dispose(); }
public async void StartReceiveAsync() { isRun = true; while(isRun) { if(!isReceive) { System.Diagnostics.Debug.WriteLine("Start Receive"); udpSocket = new Windows.Networking.Sockets.DatagramSocket(); udpSocket.MessageReceived += UdpSocket_MessageReceived; Windows.Networking.HostName hostName = null; IReadOnlyList<Windows.Networking.HostName> networkinfo = Windows.Networking.Connectivity.NetworkInformation.GetHostNames(); foreach (Windows.Networking.HostName h in networkinfo) { if (h.IPInformation != null) { Windows.Networking.Connectivity.IPInformation ipinfo = h.IPInformation; if (h.RawName == IPAddr) { hostName = h; break; } } } if (hostName != null) await udpSocket.BindEndpointAsync(hostName, Port); else await udpSocket.BindServiceNameAsync(Port); outstm = await udpSocket.GetOutputStreamAsync(new Windows.Networking.HostName("255.255.255.255"), "49002"); await outstm.FlushAsync(); Windows.Storage.Streams.DataWriter dw = new Windows.Storage.Streams.DataWriter(outstm); dw.WriteString("Start Receive"); await dw.StoreAsync(); isReceive = true; } else { if(CurrentStat.GPSStatus !=null & CurrentStat.ATTStatus != null) { if (onXPlaneStatReceived != null) onXPlaneStatReceived.Invoke(this, CurrentStat); } System.Diagnostics.Debug.WriteLine("Try To Sleep"); isReceive = false; await udpSocket.CancelIOAsync(); udpSocket.MessageReceived -= UdpSocket_MessageReceived; udpSocket.Dispose(); udpSocket = null; } await Task.Delay(waitSeconds*1000); } }
public UwaUdpSocket(int localPort, string localIPAddress) { _DataAvailableSignal = new System.Threading.ManualResetEvent(false); _ReceivedData = new System.Collections.Concurrent.ConcurrentQueue <ReceivedUdpData>(); this._LocalPort = localPort; _Socket = new Windows.Networking.Sockets.DatagramSocket(); _Socket.MessageReceived += _Socket_MessageReceived; BindSocket(); }
public async void get() { 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. string serverPort = "21777"; //Bind the socket to the serverPort so that we can start listening for UDP messages from the UDP echo client. await socket.BindServiceNameAsync(serverPort); }
public UwaUdpSocket(int localPort, string localIPAddress) { _DataAvailableSignal = new System.Threading.ManualResetEvent(false); _ReceivedData = new System.Collections.Concurrent.ConcurrentQueue<ReceivedUdpData>(); this._LocalPort = localPort; _Socket = new Windows.Networking.Sockets.DatagramSocket(); _Socket.MessageReceived += _Socket_MessageReceived; BindSocket(); }
public UwaUdpSocket(int localPort) { _DataAvailableSignal = new System.Threading.ManualResetEvent(false); _ReceivedData = new System.Collections.Concurrent.ConcurrentQueue<ReceivedUdpData>(); this.localPort = localPort; _Socket = new Windows.Networking.Sockets.DatagramSocket(); _Socket.MessageReceived += _Socket_MessageReceived; var t = _Socket.BindServiceNameAsync(this.localPort.ToString()).AsTask(); t.Wait(); }
public static void ServerDatagramSocket_MessageReceived( Windows.Networking.Sockets.DatagramSocket sender, Windows.Networking.Sockets.DatagramSocketMessageReceivedEventArgs args) { string respond; using (DataReader dataReader = args.GetDataReader()) { respond = dataReader.ReadString(dataReader.UnconsumedBufferLength).Trim(); } StatusResponse = respond; }
public UwaUdpSocket(int localPort) { _DataAvailableSignal = new System.Threading.ManualResetEvent(false); _ReceivedData = new System.Collections.Concurrent.ConcurrentQueue <ReceivedUdpData>(); this.localPort = localPort; _Socket = new Windows.Networking.Sockets.DatagramSocket(); _Socket.MessageReceived += _Socket_MessageReceived; var t = _Socket.BindServiceNameAsync(this.localPort.ToString()).AsTask(); t.Wait(); }
private async void ClientDatagramSocket_MessageReceived(Windows.Networking.Sockets.DatagramSocket sender, Windows.Networking.Sockets.DatagramSocketMessageReceivedEventArgs args) { string response; using (DataReader dataReader = args.GetDataReader()) { response = dataReader.ReadString(dataReader.UnconsumedBufferLength).Trim(); } await this.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => this.clientListBox.Items.Add(string.Format("client received the response: \"{0}\"", response))); sender.Dispose(); await this.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => this.clientListBox.Items.Add("client closed its socket")); }
public void Dispose() { try { var socket = _Socket; if (socket != null) { _Socket = null; socket.Dispose(); } } finally { GC.SuppressFinalize(this); } }
public void Dispose() { try { var socket = _Socket; if (socket != null) { _Socket = null; socket.Dispose(); } } finally { GC.SuppressFinalize(this); } }
public async static Task SendMessage(Windows.Networking.Sockets.DatagramSocket socket, HostName hostName, string port, string request) { UTF8Encoding utf8 = new UTF8Encoding(); var temp = utf8.GetBytes(request); string request8 = utf8.GetString(temp); using (Stream outputStream = (await socket.GetOutputStreamAsync(hostName, port)).AsStreamForWrite()) { using (var streamWriter = new StreamWriter(outputStream)) { await streamWriter.WriteAsync(request8); await streamWriter.FlushAsync(); } } }
public UwaUdpSocket(string ipAddress, int multicastTimeToLive, int localPort) { _DataAvailableSignal = new System.Threading.ManualResetEvent(false); _ReceivedData = new System.Collections.Concurrent.ConcurrentQueue<ReceivedUdpData>(); this.ipAddress = ipAddress; this.multicastTimeToLive = multicastTimeToLive; this.localPort = localPort; _Socket = new Windows.Networking.Sockets.DatagramSocket(); //_Socket.Control.MulticastOnly = true; _Socket.MessageReceived += _Socket_MessageReceived; var t = _Socket.BindServiceNameAsync(this.localPort.ToString()).AsTask(); t.Wait(); _Socket.JoinMulticastGroup(new Windows.Networking.HostName(Rssdp.Infrastructure.SsdpConstants.MulticastLocalAdminAddress)); }
private void ServerDatagramSocket_MessageReceived(Windows.Networking.Sockets.DatagramSocket sender, Windows.Networking.Sockets.DatagramSocketMessageReceivedEventArgs args) { Stream streamIn = args.GetDataStream().AsStreamForRead(); MemoryStream ms = ToMemoryStream(streamIn); byte[] data = ms.ToArray(); switch (ReceivingStatus) { case AWAITING_IMAGE: if (data.Length == 3) { StartReceivingImage(data); } break; default: if (data.Length == 0) { // Handle image here serverDatagramSocket.MessageReceived -= ServerDatagramSocket_MessageReceived; ReceivingStatus = AWAITING_IMAGE; byte[] processingBuffer = ImageBuffer; ImageBuffer = null; DisplayImage(processingBuffer); ImgCount++; // showImage = false; Debug.WriteLine(ImgCount); } // It's only possible for start packets to be of size 3 (others must be >= 4) else if (data.Length == 3) { StartReceivingImage(data); } else { int ind = data[0]; ind |= ((data[1] & 0xff) << 8); ind |= ((data[2] & 0xff) << 16); for (int i = 0; i < data.Length - 3; ++i) { ImageBuffer[(ind * PACKET_SIZE) + i] = data[i + 3]; } } break; } }
public override void StartServer() { #if NETFX_CORE this.client = new Windows.Networking.Sockets.DatagramSocket(); this.client.MessageReceived += this.MessageReceived; this.client.BindServiceNameAsync(this.port.ToString()).AsTask().Wait(); #else this.endPoint = new IPEndPoint(IPAddress.Any, this.port); this.clientEndPoint = new IPEndPoint(IPAddress.Any, this.port); this.client = new UdpClient(this.endPoint); this.client.EnableBroadcast = true; this.client.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true); this.client.BeginReceive(new AsyncCallback(this.ReceivedPacket), null); #endif InternalNGDebug.LogFile("Started UDPListener."); }
/// <summary> /// Stop voice recording. /// </summary> private async void StopCapture(MediaElement mediaElement) { if (Status != RecorderStatus.Recording) { return; } Debug.WriteLine("Stopping recording"); await _mediaCapture.StopRecordAsync(); Debug.WriteLine("Stop recording successful"); Status = RecorderStatus.Initial; _recordingStream.Seek(0); //mediaElement.AutoPlay = true; //mediaElement.SetSource(_recordingStream, ""); //mediaElement.Play(); //var buffer = new Windows.Storage.Streams.Buffer(4000000); //await _recordingStream.ReadAsync(buffer, buffer.Capacity, InputStreamOptions.None); //var bytes = buffer.ToArray(); var clientDatagramSocket = new Windows.Networking.Sockets.DatagramSocket(); var hostName = new Windows.Networking.HostName(HostName); await clientDatagramSocket.ConnectAsync(hostName, Port); using (var serverDatagramSocket = new Windows.Networking.Sockets.DatagramSocket()) { using (Stream outputStream = (await serverDatagramSocket.GetOutputStreamAsync(hostName, Port)).AsStreamForWrite()) { var buffer = new Windows.Storage.Streams.Buffer(MaxUdpPackageSize); while (true) { var retrievedBuffer = _recordingStream.ReadAsync(buffer, MaxUdpPackageSize, InputStreamOptions.None).GetResults(); if (retrievedBuffer == null || retrievedBuffer.Length < 1) { break; } outputStream.Write(retrievedBuffer.ToArray(), 0, (int)retrievedBuffer.Length); outputStream.Flush(); } } } }
public UwaUdpSocket(string ipAddress, int multicastTimeToLive, int localPort) { _DataAvailableSignal = new System.Threading.ManualResetEvent(false); _ReceivedData = new System.Collections.Concurrent.ConcurrentQueue <ReceivedUdpData>(); this.ipAddress = ipAddress; this.multicastTimeToLive = multicastTimeToLive; this.localPort = localPort; _Socket = new Windows.Networking.Sockets.DatagramSocket(); //_Socket.Control.MulticastOnly = true; _Socket.MessageReceived += _Socket_MessageReceived; var t = _Socket.BindServiceNameAsync(this.localPort.ToString()).AsTask(); t.Wait(); _Socket.JoinMulticastGroup(new Windows.Networking.HostName(Rssdp.Infrastructure.SsdpConstants.MulticastLocalAdminAddress)); }
public async void StartServer() { try { var serverDatagramSocket = new Windows.Networking.Sockets.DatagramSocket(); // The ConnectionReceived event is raised when connections are received. serverDatagramSocket.MessageReceived += ServerDatagramSocket_MessageReceived; // Start listening for incoming TCP connections on the specified port. You can specify any port that's not currently in use. await serverDatagramSocket.BindServiceNameAsync(ServerPortNumber); } catch (Exception ex) { Windows.Networking.Sockets.SocketErrorStatus webErrorStatus = Windows.Networking.Sockets.SocketError.GetStatus(ex.GetBaseException().HResult); Debug.WriteLine("failed to bind"); } }
public UwaUdpSocket(string ipAddress, int multicastTimeToLive, int localPort, string localIPAddress) { _LocalIPAddress = localIPAddress; _DataAvailableSignal = new System.Threading.ManualResetEvent(false); _ReceivedData = new System.Collections.Concurrent.ConcurrentQueue <ReceivedUdpData>(); _MulticastTimeToLive = multicastTimeToLive; _LocalPort = localPort; _Socket = new Windows.Networking.Sockets.DatagramSocket(); #if !WINRT _Socket.Control.MulticastOnly = true; #endif _Socket.MessageReceived += _Socket_MessageReceived; BindSocket(); _Socket.JoinMulticastGroup(new Windows.Networking.HostName(ipAddress)); }
private void ServerDatagramSocket_MessageReceived(Windows.Networking.Sockets.DatagramSocket sender, Windows.Networking.Sockets.DatagramSocketMessageReceivedEventArgs args) { Stream streamIn = args.GetDataStream().AsStreamForRead(); MemoryStream ms = ToMemoryStream(streamIn); byte[] data = ms.ToArray(); switch (ReceivingStatus) { case AWAITING_IMAGE: if (data.Length == START_PACKET_SIZE) { StartReceivingImage(data); } break; default: if (data.Length == 0) { // Handle image here byte[] processingBuffer = ImageBuffer; ImageBuffer = null; int imageType = ReceivingStatus; ReceivingStatus = AWAITING_IMAGE; // TODO: Launch DisplayImage in a new thread DisplayImage(processingBuffer, imageType); } // It's only possible for start packets to be of size 3 (others must be >= 4) else if (data.Length == START_PACKET_SIZE) { StartReceivingImage(data); } else { int ind = data[0]; ind |= ((data[1] & 0xff) << 8); ind |= ((data[2] & 0xff) << 16); for (int i = 0; i < data.Length - NORMAL_PACKET_INDEX_BYTES; ++i) { ImageBuffer[(ind * PACKET_SIZE) + i] = data[i + NORMAL_PACKET_INDEX_BYTES]; } } break; } }
public UwaUdpSocket(string ipAddress, int multicastTimeToLive, int localPort, string localIPAddress) { _LocalIPAddress = localIPAddress; _DataAvailableSignal = new System.Threading.ManualResetEvent(false); _ReceivedData = new System.Collections.Concurrent.ConcurrentQueue<ReceivedUdpData>(); _LocalIPAddress = ipAddress; _MulticastTimeToLive = multicastTimeToLive; _LocalPort = localPort; _Socket = new Windows.Networking.Sockets.DatagramSocket(); #if !WINRT _Socket.Control.MulticastOnly = true; #endif _Socket.MessageReceived += _Socket_MessageReceived; BindSocket(); _Socket.JoinMulticastGroup(new Windows.Networking.HostName(Rssdp.Infrastructure.SsdpConstants.MulticastLocalAdminAddress)); }
private static void Current_MessageReceived(Windows.Networking.Sockets.DatagramSocket sender, MessageModel message) { lock (o) { var client = UDPServer.Current.ClientList.FirstOrDefault(p => p.Token.Equals(message.Token)); if (client != null) { //if (!client.HostName.Equals(args.RemoteAddress.RawName)) //{ // client.HostName = args.RemoteAddress.RawName; //} switch (message.Type) { case MessageType.UpdateAll: SendAll(client); break; case MessageType.PlayerStateChanged: ChangePlayerState(message.Content); break; case MessageType.UpdateTrack: DataReader reader = DataReader.FromBuffer(message.Content); int index = reader.ReadInt32(); Debug.WriteLine("接收到的track为: " + index); if (index >= 0 && index <= MediaController.Current.Playlist.Count) { MediaController.Current.ChangeTrack(index); } break; case MessageType.UpdatePosition: break; case MessageType.ChangeVolume: break; default: break; } } } }
/// <summary> /// Retrieve the current network time from ntp server "time.windows.com". /// </summary> public async void GetNetworkTime(string ntpServer) { averageNtpRTT = 0; //reset currentNtpQueryCount = 0; //reset minNtpRTT = -1; //reset //NTP uses UDP ntpSocket = new Windows.Networking.Sockets.DatagramSocket(); ntpSocket.MessageReceived += OnNTPTimeReceived; if (ntpQueryTimer == null) { ntpQueryTimer = new Windows.UI.Xaml.DispatcherTimer(); ntpQueryTimer.Tick += NTPQueryTimeout; ntpQueryTimer.Interval = new TimeSpan(0, 0, 5); //5 seconds } if (ntpRTTIntervalTimer == null) { ntpRTTIntervalTimer = new Windows.UI.Xaml.DispatcherTimer(); ntpRTTIntervalTimer.Tick += SendNTPQuery; ntpRTTIntervalTimer.Interval = new TimeSpan(0, 0, 0, 0, 200); //200ms } ntpQueryTimer.Start(); try { //The UDP port number assigned to NTP is 123 await ntpSocket.ConnectAsync(new Windows.Networking.HostName(ntpServer), "123"); ntpRTTIntervalTimer.Start(); } catch (Exception e) { Debug.WriteLine($"NtpSync: Exception when connect socket: {e.Message}"); ntpResponseMonitor.Stop(); ReportNtpSyncStatus(false); } }
private async void UdpClient() { try { socket = new Windows.Networking.Sockets.DatagramSocket(); socket.MessageReceived += Socket_MessageReceived; serverHost = new Windows.Networking.HostName(serverIP); await socket.ConnectAsync(serverHost, port); udpReady = true; ConnectButton.Content = "Connected!"; } catch (Exception e) { } }
private async void StartClient() { try { // Create the DatagramSocket and establish a connection to the echo server. var clientDatagramSocket = new Windows.Networking.Sockets.DatagramSocket(); clientDatagramSocket.MessageReceived += ClientDatagramSocket_MessageReceived; // 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 about to bind..."); await clientDatagramSocket.BindServiceNameAsync(UDPSocketPage.ClientPortNumber); this.clientListBox.Items.Add(string.Format("client is bound to port number {0}", UDPSocketPage.ClientPortNumber)); // Send a request to the echo server. string request = "Hello, World!"; using (var serverDatagramSocket = new Windows.Networking.Sockets.DatagramSocket()) { using (Stream outputStream = (await serverDatagramSocket.GetOutputStreamAsync(hostName, UDPSocketPage.ServerPortNumber)).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)); } 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 void _Socket_MessageReceived(Windows.Networking.Sockets.DatagramSocket sender, Windows.Networking.Sockets.DatagramSocketMessageReceivedEventArgs args) { using (var reader = args.GetDataReader()) { var data = new ReceivedUdpData() { ReceivedBytes = Convert.ToInt32(reader.UnconsumedBufferLength), ReceivedFrom = new UdpEndPoint() { IPAddress = args.RemoteAddress.RawName, Port = Convert.ToInt32(args.RemotePort) } }; data.Buffer = new byte[data.ReceivedBytes]; reader.ReadBytes(data.Buffer); _ReceivedData.Enqueue(data); _DataAvailableSignal.Set(); } }
public async void StopReceive() { try { isRun = false; if(isReceive) { await udpSocket.CancelIOAsync(); udpSocket.MessageReceived -= UdpSocket_MessageReceived; isReceive = false; } } finally { if(udpSocket != null) { udpSocket.Dispose(); udpSocket = null; } _Instance = null; } }
/// <summary> /// Retrieve the current network time from ntp server "time.windows.com". /// </summary> public async void GetNetworkTime(string ntpServer) { averageNtpRTT = 0; //reset currentNtpQueryCount = 0; //reset minNtpRTT = -1; //reset //NTP uses UDP ntpSocket = new Windows.Networking.Sockets.DatagramSocket(); ntpSocket.MessageReceived += OnNTPTimeReceived; if (ntpQueryTimer == null) { ntpQueryTimer = new Windows.UI.Xaml.DispatcherTimer(); ntpQueryTimer.Tick += NTPQueryTimeout; ntpQueryTimer.Interval = new TimeSpan(0, 0, 5); //5 seconds } if (ntpRTTIntervalTimer == null) { ntpRTTIntervalTimer = new Windows.UI.Xaml.DispatcherTimer(); ntpRTTIntervalTimer.Tick += SendNTPQuery; ntpRTTIntervalTimer.Interval = new TimeSpan(0, 0, 0, 0, 200); //200ms } ntpQueryTimer.Start(); try { //The UDP port number assigned to NTP is 123 await ntpSocket.ConnectAsync(new Windows.Networking.HostName(ntpServer), "123"); ntpRTTIntervalTimer.Start(); } catch (Exception e) { Debug.WriteLine($"NtpSync: Exception when connect socket: {e.Message}"); ntpResponseMonitor.Stop(); ReportNtpSyncStatus(false); } }
private void HandlerWithLambaExample() { Windows.Networking.Sockets.DatagramSocket socket = new Windows.Networking.Sockets.DatagramSocket(); socket.MessageReceived += new TypedEventHandler< Windows.Networking.Sockets.DatagramSocket, Windows.Networking.Sockets.DatagramSocketMessageReceivedEventArgs>((datagramSocket, eventArgs) => { // Empty handler. }); }