private void OnMessageReceived(DatagramSocket sender, DatagramSocketMessageReceivedEventArgs args) { var stream = args.GetDataStream().AsStreamForRead(); int count = stream.Read(_buffer, 0, _buffer.Length); if (count > 0) { if (_bufferEndPoint == null || !_bufferEndPoint.HostName.IsEqual(args.RemoteAddress) || !_bufferEndPoint.PortStr.Equals(args.RemotePort)) { _bufferEndPoint = new NetEndPoint(args.RemoteAddress, args.RemotePort); } _onMessageReceived(_buffer, count, 0, _bufferEndPoint); } }
private async void Timer_SendStatusBeacon(object sender, System.Timers.ElapsedEventArgs e) { using (var ds = new DatagramSocket()) { using (var opS = new DataWriter(await ds.GetOutputStreamAsync(new HostName("255.255.255.255"), "8377"))) { opS.WriteBuffer(Encoding.UTF8.GetBytes((await GetCurrentStatus()).Stringify()).AsBuffer()); await opS.StoreAsync(); //Debug.WriteLine(jsonStatus.Stringify()); await opS.FlushAsync(); opS.DetachStream(); } } }
public static async void GetTime() { DatagramSocket socket = new DatagramSocket(); socket.MessageReceived += socket_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(); } }
public void ConnectListener(int port) { #if WINDOWS_UWP if (task == null) { task = Task.Run(async() => { socket = new DatagramSocket(); socket.MessageReceived += MessageReceived; await socket.BindServiceNameAsync(port.ToString()); }); } #else udpclient = new UdpClient(port); udpclient.BeginReceive(new AsyncCallback(ReceiveCallback), udpclient); #endif }
private static async Task <string> DnsLookup(string remoteHostName) { IReadOnlyList <EndpointPair> data = await DatagramSocket.GetEndpointPairsAsync(new HostName(remoteHostName), "0").AsTask().ConfigureAwait(false); if (data != null && data.Count > 0) { foreach (EndpointPair item in data) { if (item != null && item.RemoteHostName != null && item.RemoteHostName.Type == HostNameType.Ipv4) { return(item.RemoteHostName.CanonicalName); } } } return(string.Empty); }
public static void TearDownSockets() { if (ab != null) { ab.Dispose(); ab = null; } if (scr != null) { scr.Dispose(); scr = null; } SocketsAreConnected = false; }
public void StopSend() { try { if (msocketSend != null) { // msocketSend.MessageReceived -= UDPMulticastMessageReceived; msocketSend.Dispose(); msocketSend = null; } } catch (Exception e) { System.Diagnostics.Debug.WriteLine("Exception while stopping listening: " + e.Message); } }
private void Socket_MessageReceived(DatagramSocket sender, DatagramSocketMessageReceivedEventArgs args) { DataReader networkDataReader = args.GetDataReader(); int len = networkDataReader.ReadInt32(); byte[] data = new byte[len]; networkDataReader.ReadBytes(data); NetInMessage message = new NetInMessage(data); lock (lockObj) { m_incomingMessageQueue.Enqueue(message); } }
public async void Start() { socket = new DatagramSocket(); socket.MessageReceived += socket_MessageReceived; try { await socket.BindServiceNameAsync(config.Port.ToString()); } catch (Exception e) { Debug.Log(e.ToString()); Debug.Log(SocketError.GetStatus(e.HResult).ToString()); return; } }
private void OnSocketMessageReceived(DatagramSocket sender, DatagramSocketMessageReceivedEventArgs args) { try { using (var reader = args.GetDataReader()) { byte[] response = new byte[48]; reader.ReadBytes(response); myResultCompletionSource.TrySetResult(ParseNetworkTime(response)); } } catch (Exception ex) { myResultCompletionSource.TrySetException(ex); } }
public override bool StartPing(string host) { lock (this.syncer) { this.Init(); EndpointPair endPoint = new EndpointPair(null, string.Empty, new HostName(host), "5055"); this.sock = new DatagramSocket(); this.sock.MessageReceived += this.OnMessageReceived; IAsyncAction result = this.sock.ConnectAsync(endPoint); result.Completed = this.OnConnected; this.DebugString += " End StartPing"; return(true); } }
/// <summary>Constructor</summary> /// <param name="program">program name</param> /// <param name="host">host where the Rpc server program is started</param> /// <param name="port">port where the Rpc server program is listening to</param> /// <param name="progNumber">program number as defined in RFC 1050</param> /// <param name="lowProgVersion">lowest version of the specification supported</param> /// <param name="highProgVersion">highest version of the specification supported</param> /// <param name="registrationSocket"> /// if not null, use this socket to register /// with portmap daemon /// </param> /// <param name="allowInsecurePorts"> /// true to allow client connections from /// unprivileged ports, false otherwise /// </param> protected internal RpcProgram(string program, string host, int port, int progNumber , int lowProgVersion, int highProgVersion, DatagramSocket registrationSocket, bool allowInsecurePorts) { // Ephemeral port is chosen later this.program = program; this.host = host; this.port = port; this.progNumber = progNumber; this.lowProgVersion = lowProgVersion; this.highProgVersion = highProgVersion; this.registrationSocket = registrationSocket; this.allowInsecurePorts = allowInsecurePorts; Log.Info("Will " + (allowInsecurePorts ? string.Empty : "not ") + "accept client " + "connections from unprivileged ports"); }
/// <summary> /// MessageReceived event /// </summary> /// <param name="socket"></param> /// <param name="eventArguments"></param> void MessageReceived(DatagramSocket socket, DatagramSocketMessageReceivedEventArgs eventArguments) { try { uint stringLength = eventArguments.GetDataReader().UnconsumedBufferLength; string receivedMessage = eventArguments.GetDataReader().ReadString(stringLength); var ignore = Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () => do_job(eventArguments.RemoteAddress.ToString(), receivedMessage, eventArguments.RemotePort.ToString(), eventArguments.LocalAddress.ToString())); } catch (Exception ex) { //discard any exceptions // } }
async void RunSenderTask() { var dmxPacket = Packet.PacketBuilder.GetDmxPacket(new byte[512]); while (true) // boucle infinie { resetUdpDatagram = false; if (string.IsNullOrEmpty(_targetNodeIp)) { await Task.Delay(1000); } else { using (var udpSocket = new DatagramSocket()) // creation de la socjet udp { udpSocket.Control.QualityOfService = SocketQualityOfService.LowLatency; await udpSocket.ConnectAsync(new HostName(_targetNodeIp), $"{this.TargetNodePort}"); using (var writer = new DataWriter(udpSocket.OutputStream)) { try { while (!resetUdpDatagram) // tant que pas de reset de la socket { cancelTokenSource.Token.ThrowIfCancellationRequested(); if (!_pause) { if (copyDmxBufferCallback != null) { copyDmxBufferCallback(dmxPacket, Packet.PacketBuilder.DmxPacketPayloadOffset); } writer.WriteBytes(dmxPacket); await writer.StoreAsync(); } await Task.Delay(40); } Debug.WriteLine($"Ending loop DMX sender to reset udpdatagram"); } catch (Exception ex) { Debug.WriteLine($"EXCEPTION : ArtNetPoller.RunPollerTask() : {ex.ToString()}"); } } } } } }
private void HandleIncomingMessages(DatagramSocket sender, DatagramSocketMessageReceivedEventArgs e) { //(await e.RemoteAddress.IPInformation.NetworkAdapter.GetConnectedProfileAsync()).GetNetworkNames(); if (hostNames != null && hostNames.Contains(e.RemoteAddress.ToString())) { return; } var remote = e.RemoteAddress; var local = e.LocalAddress; var reader = e.GetDataReader(); byte[] data = new byte[reader.UnconsumedBufferLength]; reader.ReadBytes(data); var msg = ParseMessage(data); if (msg.Type == MessageType.DeviceStateService) { ProcessDeviceDiscoveryMessage(e.RemoteAddress, e.RemotePort, msg); } else { if (taskCompletions.ContainsKey(msg.Source)) { var tcs = taskCompletions[msg.Source]; tcs(msg); } //else if (msg.Type.ToString().StartsWith("State")) //{ //} //else if (msg.Type == MessageType.DeviceAcknowledgement) //{ // if (taskCompletions.ContainsKey(msg.Source)) // { // var tcs = taskCompletions[msg.Source]; // if (!tcs.Task.IsCompleted) // tcs.SetResult(msg); // } //} else { //TODO } } System.Diagnostics.Debug.WriteLine("Received from {0}:{1}", remote.RawName, string.Join(",", (from a in data select a.ToString("X2")).ToArray())); }
/// <summary> /// Search one device on the local network with the specified name. /// </summary> /// <param name="deviceName">Friendly name of the device.</param> /// <param name="timeoutMiliseconds">Timeout to search the device.</param> /// <returns>Device with the specified name.</returns> public static async Task <IDeviceInfo> GetDevice(string deviceName, uint timeoutMiliseconds = 6000) { if (string.IsNullOrEmpty(deviceName)) { throw new ArgumentNullException("deviceName"); } if (timeoutMiliseconds == 0) { throw new InvalidOperationException("Timeout must be greater than zero."); } IDeviceInfo deviceInfo = null; var timeoutCancellationTokenSource = new CancellationTokenSource(); using (var socket = new DatagramSocket()) { socket.MessageReceived += async(sender, args) => { var reader = args.GetDataReader(); var deviceLocationUri = GetDeviceLocation(reader.ReadString(reader.UnconsumedBufferLength)); var dinfo = await GetDeviceInfo(deviceLocationUri); #if DEBUG Debug.WriteLine(string.Format("DEVICE FOUND: Name = {0}, Manufacturer = {1}, Model = {2}, Address = {3}", dinfo.FriendlyName, dinfo.Manufacturer, dinfo.Model, dinfo.UrlBase)); #endif if (dinfo.FriendlyName.Equals(deviceName)) { deviceInfo = dinfo; timeoutCancellationTokenSource.Cancel(); } }; await socket.BindEndpointAsync(null, ""); socket.JoinMulticastGroup(DialConstants.MulticastHost); var writer = new DataWriter(await socket.GetOutputStreamAsync(DialConstants.MulticastHost, DialConstants.UdpPort)); writer.WriteString(string.Format(DialConstants.MSearchMessage, DialConstants.MulticastHost, DialConstants.UdpPort)); await writer.StoreAsync(); try { await Task.Delay((int)timeoutMiliseconds, timeoutCancellationTokenSource.Token); } catch {} } return(deviceInfo); }
private void DataListener() { IPEndPoint localEndpoint = new IPEndPoint(IPAddress.Any, 0); udpClient = new UdpClient(localEndpoint); udpClient.Client.ReceiveBufferSize = 65507 * 32; udpClient.Client.SendBufferSize = 65507 * 32; IPAddress listenIP = ((IPEndPoint)udpClient.Client.LocalEndPoint).Address; int listenPort = ((IPEndPoint)udpClient.Client.LocalEndPoint).Port; _listening = true; Debug.Log("Client listening on " + listenIP.ToString() + ":" + listenPort); while (_running) { try { byte[] buffer = udpClient.Receive(ref localEndpoint);//this is the evil bastard that crashes on an ICMP message String data = Encoding.ASCII.GetString(buffer); MSG msg = new MSG(data); lock (_receiveQueueLock) { _receiveQueue.Enqueue(msg); } } catch (SocketException e) { //OK, since this was a bitch to figure out, here is some documentation for what is going on, and why we encounter exceptions when receiving data //Context: The way our multi-client-udp-middleware works: packets are sent from Client A from any available (random) port to the predefined port of Client B. //Client B then looks at the packet's originating (random) port that A used to send the packet and adds Client A to the list of clients to broadcast outgoing packets to. //When sending packets back from B to A, it will now use the (random) port as its destination. //As a consequence, here in Unity we must send and receive data with the same UdpClient using the same port. //However, on some windows machines sending data to a port where there is no listener results in an ICMP response WSAECONNRESET //E.g. see here: https://stackoverflow.com/questions/7201862/an-existing-connection-was-forcibly-closed-by-the-remote-host //(This situation can occur if Unity is started before e.g. ASAP is running; in that case there is nobody listening to our packets) //This ICMP response then silently kind of half-closes our UdpClient connection.... //Weirdly enough we can still continue sending data, but when we try to call UdpClient.Receive() it throws an exception --- EVEN IF THERE IS DATA WAITING IN THE BUFFER AT THAT VERY MOMENT. //Even weirdly-er, we can just ignore the exception and continue using the udpClient for sending and receiving...! //The current workaround simply catches the exception and ignores it :) //Unfortunately, the incoming packet that caused the exception is lost } } udpClient.Close(); }
async Task OpenAsync() { #if WINDOWS_UWP HostName host = new HostName(this.hostName); var endpointPairs = await DatagramSocket.GetEndpointPairsAsync(host, ""); var ep = endpointPairs.First(); this.serverAddress = IPAddress.Parse(ep.RemoteHostName.RawName); #else this.serverAddress = Dns.GetHostEntry(this.hostName).AddressList[0]; #endif if (this.TryStateTransition(TransportState.NotInitialized, TransportState.Opening)) { try { this.channel = await this.channelFactory(this.serverAddress, ProtocolGatewayPort); } catch (Exception ex) when(!ex.IsFatal()) { this.OnError(ex); throw; } this.ScheduleCleanup(async() => { this.disconnectAwaitersCancellationSource.Cancel(); if (this.channel == null) { return; } if (this.channel.Active) { await this.channel.WriteAsync(DisconnectPacket.Instance); } if (this.channel.Open) { await this.channel.CloseAsync(); } }); } await this.connectCompletion.Task; // Codes_SRS_CSHARP_MQTT_TRANSPORT_18_031: `OpenAsync` shall subscribe using the '$iothub/twin/res/#' topic filter await this.SubscribeTwinResponsesAsync(); }
public async void SearchForDevices() { var socket = new DatagramSocket(); socket.MessageReceived += async(sender, args) => { DataReader reader = args.GetDataReader(); uint count = reader.UnconsumedBufferLength; string data = reader.ReadString(count); var response = new Dictionary <string, string>(); foreach ( string x in data.Split(new[] { "\r\n", "\n" }, StringSplitOptions.None)) { if (x.Contains(":")) { string[] strings = x.Split(':'); response.Add(strings[0].ToLower(), x.Remove(0, strings[0].Length + 1)); } } Device device = await GetXml(response); Debug.WriteLine("Device found"); if (DeviceFound != null) { DeviceFound(this, new DeviceFoundEventArgs(device)); } }; IOutputStream stream = await socket.GetOutputStreamAsync(new HostName("239.255.255.250"), "1900"); const string message = "M-SEARCH * HTTP/1.1\r\n" + "HOST: 239.255.255.250:1900\r\n" + "ST:upnp:rootdevice\r\n" + "MAN:\"ssdp:discover\"\r\n" + "MX:3\r\n\r\n"; var writer = new DataWriter(stream) { UnicodeEncoding = UnicodeEncoding.Utf8 }; writer.WriteString(message); await writer.StoreAsync(); }
static async void multicastSocket_MessageReceived(DatagramSocket sender, DatagramSocketMessageReceivedEventArgs eventArguments) { try { HostName remoteHostAddress = eventArguments.RemoteAddress; uint len = eventArguments.GetDataReader().UnconsumedBufferLength; string message = eventArguments.GetDataReader().ReadString(len).Trim(); int p = message.IndexOf(':'); if (p != -1) { string serverLogToken = message.Substring(0, p); int port = Int32.Parse(message.Substring(p + 1)); if (serverLogToken == logToken && port > 0 && port < 65535) { Debug.WriteLine("[LOGGER] Found a Titanium log server: " + remoteHostAddress.DisplayName + ":" + port); try { tcpSocket = new StreamSocket(); tcpSocket.Control.KeepAlive = true; await tcpSocket.ConnectAsync(remoteHostAddress, port.ToString()); tcpWriter = new DataWriter(tcpSocket.OutputStream); // shutdown the multicast socket and start the tcp connection multicastSocket.Dispose(); } catch { if (tcpWriter != null) { tcpWriter.Dispose(); tcpWriter = null; } if (tcpSocket != null) { tcpSocket.Dispose(); tcpSocket = null; } } } } } catch (Exception ex) { if (SocketError.GetStatus(ex.HResult) == SocketErrorStatus.Unknown) { throw; } Debug.WriteLine(ex.ToString()); } }
public async Task SendMessage(byte msgType, byte[] message, byte[] host) { socket = new DatagramSocket(); string _host = host[0].ToString() + "." + host[1].ToString() + "." + host[2].ToString() + "." + host[3].ToString(); using (var stream = await socket.GetOutputStreamAsync(new HostName(_host), udptPort)) { using (var writer = new DataWriter(stream)) { writer.WriteByte(msgType); writer.WriteInt32(message.Length); writer.WriteBytes(message); await writer.StoreAsync(); } } socket.Dispose(); }
/// <exception cref="System.IO.IOException"/> public RpcProgramMountd(NfsConfiguration config, DatagramSocket registrationSocket , bool allowInsecurePorts) : base("mountd", "localhost", config.GetInt(NfsConfigKeys.DfsNfsMountdPortKey, NfsConfigKeys .DfsNfsMountdPortDefault), Program, Version1, Version3, registrationSocket, allowInsecurePorts ) { // Note that RPC cache is not enabled exports = new AList <string>(); exports.AddItem(config.Get(NfsConfigKeys.DfsNfsExportPointKey, NfsConfigKeys.DfsNfsExportPointDefault )); this.hostsMatcher = NfsExports.GetInstance(config); this.mounts = Sharpen.Collections.SynchronizedList(new AList <MountEntry>()); UserGroupInformation.SetConfiguration(config); SecurityUtil.Login(config, NfsConfigKeys.DfsNfsKeytabFileKey, NfsConfigKeys.DfsNfsKerberosPrincipalKey ); this.dfsClient = new DFSClient(NameNode.GetAddress(config), config); }
private void UdpMessageReceived(DatagramSocket sender, DatagramSocketMessageReceivedEventArgs args) { try { using (DataReader dataReader = args.GetDataReader()) { IBuffer buffer = dataReader.ReadBuffer(dataReader.UnconsumedBufferLength); byte[] bytes = buffer.ToArray(); Debug.WriteLine($"UDP receiving (from \"{args.RemoteAddress}\"): {string.Join(", ", bytes.Select(x => x.ToString("X2")))} ({bytes.Length} byte(s))."); } } catch (Exception exception) { Debug.WriteLine("UDP receive exception: " + exception); } }
/// <summary> /// Message received handler /// </summary> /// <param name="socket">The socket object</param> /// <param name="eventArguments">The datagram event information</param> async void MessageReceived(DatagramSocket socket, DatagramSocketMessageReceivedEventArgs eventArguments) { object outObj; if (CoreApplication.Properties.TryGetValue("remotePeer", out outObj)) { EchoMessage((RemotePeer)outObj, eventArguments); return; } // We do not have an output stream yet so create one. try { IOutputStream outputStream = await socket.GetOutputStreamAsync( eventArguments.RemoteAddress, eventArguments.RemotePort); // It might happen that the OnMessage was invoked more than once before the GetOutputStreamAsync // completed. In this case we will end up with multiple streams - make sure we have just one of it. RemotePeer peer; lock (this) { if (CoreApplication.Properties.TryGetValue("remotePeer", out outObj)) { peer = (RemotePeer)outObj; } else { peer = new RemotePeer(outputStream, eventArguments.RemoteAddress, eventArguments.RemotePort); CoreApplication.Properties.Add("remotePeer", peer); } } EchoMessage(peer, eventArguments); } 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; } NotifyUserFromAsyncThread("Connect failed with error: " + exception.Message, NotifyType.ErrorMessage); } }
public static async Task SendStringUdpAsync(HostName remoteHost, string remotePort, OSCPacket packet) { var socket = new DatagramSocket(); //socket.MessageReceived += SocketOnMessageReceived; using (var stream = await socket.GetOutputStreamAsync(remoteHost, remotePort)) { using (var writer = new DataWriter(stream)) { // var data = Encoding.UTF8.GetBytes(message); writer.WriteBytes(packet.Bytes); writer.StoreAsync(); } } }
/// <summary> /// This is the click handler for the 'CloseSockets' button. /// </summary> /// <param name="sender">Object for which the event was generated.</param> /// <param name="e">Event's parameters.</param> private void CloseSockets_Click(object sender, RoutedEventArgs e) { object outValue; if (CoreApplication.Properties.TryGetValue("clientDataWriter", out outValue)) { // Remove the data writer from the list of application properties as we are about to close it. CoreApplication.Properties.Remove("clientDataWriter"); DataWriter dataWriter = (DataWriter)outValue; // To reuse the socket with other data writer, application has to detach the stream from the writer // before disposing it. This is added for completeness, as this sample closes the socket in // very next block. dataWriter.DetachStream(); dataWriter.Dispose(); } if (CoreApplication.Properties.TryGetValue("clientSocket", out outValue)) { // Remove the socket from the list of application properties as we are about to close it. CoreApplication.Properties.Remove("clientSocket"); DatagramSocket socket = (DatagramSocket)outValue; socket.Dispose(); } if (CoreApplication.Properties.TryGetValue("listener", out outValue)) { // Remove the listener from the list of application properties as we are about to close it. CoreApplication.Properties.Remove("listener"); DatagramSocket listener = (DatagramSocket)outValue; listener.Dispose(); } if (CoreApplication.Properties.ContainsKey("remotePeer")) { // Remove the remote perr from the list of application properties. CoreApplication.Properties.Remove("remotePeer"); } if (CoreApplication.Properties.ContainsKey("connected")) { CoreApplication.Properties.Remove("connected"); } rootPage.NotifyUser("Socket and listener closed", NotifyType.StatusMessage); }
//async private async void ServerSocket_MessageReceived(DatagramSocket sender, DatagramSocketMessageReceivedEventArgs args) { Debug.Log("MessageReceivedEvent"); if (ReceivingStatus != AWAITING_IMAGE) { return; // dont do anything if not ready to receive } await System.Threading.Tasks.Task.Run(() => { Debug.Log("Getting Data Async"); Stream streamIn = args.GetDataStream().AsStreamForRead(); byte[] data = ToMemoryStream(streamIn).ToArray(); Debug.Log("Data array created of length " + data.Length); // enqueue all, continually stack // used for managing events, creates a group of actions ProcessPacket(data); }); }
/// <summary> /// Opens the server at the given port and starts the listener thread. /// </summary> /// #if NETFX_CORE public async void Connect() { Debug.Log("Waiting for a connection..."); socket = new DatagramSocket(); socket.MessageReceived += Socket_MessageReceived; try { await socket.BindEndpointAsync(null, _localPort.ToString()); } catch (Exception e) { Debug.Log(e.ToString()); Debug.Log(SocketError.GetStatus(e.HResult).ToString()); return; } }
public async override void StartServer(string address, int port) { try { socket_ = new DatagramSocket(); socket_.MessageReceived += OnMessage; rcvHost = new HostName(address); await socket_.BindServiceNameAsync(port.ToString()); socket_.JoinMulticastGroup(rcvHost);//この辺でjoinする } catch (Exception e) { Debug.LogError(e.ToString()); } }
private async Task InitializeAsync() { //NetworkInformation.GetConnectionProfiles().Select(ni=>ni.NetworkAdapter.) var connectionProfile = NetworkInformation.GetConnectionProfiles().LastOrDefault( p => p.GetNetworkConnectivityLevel() != NetworkConnectivityLevel.None); //using (var stream = await _socket.GetOutputStreamAsync(new HostName(IpProvider.BroadcastAddress), Port)) hostNames = NetworkInformation.GetHostNames().Select(t => t.ToString()).ToList(); _socket = new DatagramSocket(); _socket.Control.DontFragment = true; _socket.MessageReceived += HandleIncomingMessages; //foreach (var adapter in NetworkInformation.GetConnectionProfiles().Select(t=>t.NetworkAdapter).Distinct()) //{ // await _socket.BindServiceNameAsync(Port, adapter); //, connectionProfile.NetworkAdapter); //} await _socket.BindServiceNameAsync(Port, connectionProfile.NetworkAdapter); }
public void Close() { _datagramSocket.Dispose(); _datagramSocket = null; ClearPeers(); }
private void OnMessageReceived(DatagramSocket sender, DatagramSocketMessageReceivedEventArgs args) { var result = args.GetDataStream().ReadAsync(_buffer, _buffer.Capacity, InputStreamOptions.None).AsTask().Result; int length = (int)result.Length; if (length <= 0) return; if (_bufferEndPoint == null || !_bufferEndPoint.HostName.IsEqual(args.RemoteAddress) || !_bufferEndPoint.PortStr.Equals(args.RemotePort)) { _bufferEndPoint = new NetEndPoint(args.RemoteAddress, args.RemotePort); } _onMessageReceived(_byteBuffer, length, 0, _bufferEndPoint); }
private void Socket_MessageReceived(DatagramSocket sender, DatagramSocketMessageReceivedEventArgs args) { try { var connectionKey = GetConnectionKey(args.RemoteAddress, args.RemotePort); Connection connection; bool newConnection = false; lock (this.connectionCache) { if (!this.connectionCache.TryGetValue(connectionKey, out connection)) { connection = new Connection(); this.connectionCache.Add(connectionKey, connection); newConnection = true; } connection.Touch(); } var reader = args.GetDataReader(); string received = reader.ReadString(reader.UnconsumedBufferLength); var msg = DeserializeInternalMessage(received); var connectMessage = msg as Model.ConnectMessage; if (connectMessage != null) { if (newConnection) Debug.WriteLine("New connection {0}:{1} from host {2}", args.RemoteAddress, args.RemotePort, connectMessage.HostId); Debug.WriteLine("Connect from " + connectMessage.HostId); lock (this.hostIdLookup) { this.hostIdLookup[connectMessage.HostId] = connectionKey; } connection.HostId = connectMessage.HostId; // Send alive message Task.Run(async () => await SendAliveAsync(connectMessage.HostId)); } var payloadMessage = msg as Model.PayloadMessage; if (payloadMessage != null) { object payloadObject = DeserializePayload(payloadMessage.Payload); try { this.payloadReceivedAction?.Invoke(connection.HostId, payloadObject); } catch (Exception ex) { Debug.WriteLine("Exception while invoking callback with payload object " + ex.ToString()); } } } catch (Exception exception) { SocketErrorStatus socketError = SocketError.GetStatus(exception.HResult); if (socketError == SocketErrorStatus.ConnectionResetByPeer) { // This error would indicate that a previous send operation resulted in an // ICMP "Port Unreachable" message. //NotifyUserFromAsyncThread( // "Peer does not listen on the specific port. Please make sure that you run step 1 first " + // "or you have a server properly working on a remote server.", // NotifyType.ErrorMessage); } else if (socketError != SocketErrorStatus.Unknown) { //NotifyUserFromAsyncThread( // "Error happened when receiving a datagram: " + socketError.ToString(), // NotifyType.ErrorMessage); } else { throw; } } }
public bool Bind(int port) { _datagramSocket = new DatagramSocket(); _datagramSocket.Control.InboundBufferSizeInBytes = NetConstants.SocketBufferSize; _datagramSocket.Control.DontFragment = true; _datagramSocket.Control.OutboundUnicastHopLimit = NetConstants.SocketTTL; _datagramSocket.MessageReceived += OnMessageReceived; try { _datagramSocket.BindServiceNameAsync(port.ToString()).AsTask().Wait(); _datagramSocket.JoinMulticastGroup(MulticastAddressV6); _localEndPoint = new NetEndPoint(_datagramSocket.Information.LocalAddress, _datagramSocket.Information.LocalPort); } catch (Exception ex) { NetUtils.DebugWriteError("[B]Bind exception: {0}", ex.ToString()); return false; } return true; }