SendToAsync() public method

public SendToAsync ( SocketAsyncEventArgs e ) : bool
e SocketAsyncEventArgs
return bool
Beispiel #1
0
        public void SendState(X360State state)
        {
            byte[] data = state.GetState();

            if (null != this.netduinoPlusAddress)
            {
                Debug.WriteLine("Sending:" + state.ToString());
#if WINDOWS
                Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);

                SocketAsyncEventArgs socketArgs = new SocketAsyncEventArgs();

                socketArgs.RemoteEndPoint = new IPEndPoint(IPAddress.Parse(this.netduinoPlusAddress), 9999);
                socketArgs.SetBuffer(data, 0, data.Length);

                socketArgs.Completed += new EventHandler<SocketAsyncEventArgs>(delegate(object s, SocketAsyncEventArgs e) { });

                socket.SendToAsync(socketArgs);
#endif
            }
            else
            {
#if WINDOWS
                try
                {
                    if ((false == IsTheSame(data)) || (null == this.port))
                    {
                        if (null == this.port)
                        {
                            if (this.framesToIgnore-- <= 0)
                            {
                             //   if (Array.Exists<String>(SerialPort.GetPortNames(), s => s == this.portName))
                                {
                                    this.port = new SerialPort(this.portName, 115200/* this.config.ArduinoPortBaud*/, Parity.None, 8, StopBits.One);
                                    this.port.DataReceived += this.DataReceived;
                                    this.port.Open();
                                    Thread.Sleep(2000); // wait for bloody arduino nano.
                                }
                            }
                        }

                        if (null != this.port)
                        {
                            this.port.Write(data, 0, data.Length);

                            this.lastState = data;
                        }
                    }
                }
                catch (Exception ex)
                {
                    this.port = null;
                    Debug.WriteLine(ex.Message);
                    this.framesToIgnore = 60; // too lazy to do some tread sleep magic.
                }
#endif
            }
        }
Beispiel #2
0
        public Task <int> SendAsync(byte[] datagram, int bytes, IPEndPoint?endPoint)
        {
            ValidateDatagram(datagram, bytes, endPoint);

            if (endPoint is null)
            {
                return(_clientSocket.SendAsync(new ArraySegment <byte>(datagram, 0, bytes), SocketFlags.None));
            }
            else
            {
                CheckForBroadcast(endPoint.Address);
                return(_clientSocket.SendToAsync(new ArraySegment <byte>(datagram, 0, bytes), SocketFlags.None, endPoint));
            }
        }
Beispiel #3
0
        /// <summary>
        /// Sends the specified number of bytes of data to the specified endpoint, starting at the specified location in the buffer.
        /// </summary>
        /// <returns>The number of bytes sent.</returns>
        /// <param name="buffer">An array of type Byte that contains the data to be sent.</param>
        /// <param name="offset">The position in the data buffer at which to begin sending data.</param>
        /// <param name="size">The number of bytes to send.</param>
        /// <param name="remoteEP">The EndPoint that represents the destination location for the data.</param>
        internal Task <int> SendToAsync(byte [] buffer, int offset, int size, EndPoint remoteEP)
        {
            TaskCompletionSource <int> tcs = new TaskCompletionSource <int> ();
            var saea = new SocketAsyncEventArgs();

            saea.SetBuffer(buffer, offset, size);
            saea.RemoteEndPoint = remoteEP;
            saea.Completed     += (object sender, SocketAsyncEventArgs args) => { tcs.SetResult(args.BytesTransferred); };

            if (!m_socket.SendToAsync(saea))
            {
                tcs.SetResult(saea.BytesTransferred);
            }
            return(tcs.Task);
        }
Beispiel #4
0
        public void SendTo(byte[] messageData, UdpEndPoint endPoint)
        {
            if (messageData == null)
            {
                throw new ArgumentNullException("messageData");
            }
            if (endPoint == null)
            {
                throw new ArgumentNullException("endPoint");
            }

            ThrowIfDisposed();

            var args = new SocketAsyncEventArgs();

            try
            {
                args.SetBuffer(messageData, 0, messageData.Length);
                args.RemoteEndPoint = new System.Net.IPEndPoint(IPAddress.Parse(endPoint.IPAddress), endPoint.Port);

                var signal = new ManualResetEvent(false);
                try
                {
                    args.Completed += (sender, e) =>
                    {
                        signal.Set();
                    };

                    _Socket.SendToAsync(args);

                    signal.WaitOne();
                }
                finally
                {
                    signal.Dispose();
                }
            }
            catch
            {
                if (args != null)
                {
                    args.Dispose();
                }

                throw;
            }
        }
Beispiel #5
0
        public int SendUDP(byte[] bData, int nLength, System.Net.EndPoint ep)
        {
            lock (SyncRoot)
            {
                if (m_bReceive == false)
                {
                    this.LogError(MessageImportance.Highest, "error", string.Format("Can't call SendUDP, socket not valid or closed"));
                    return(0);
                }

                LogMessage(MessageImportance.Lowest, this.OurGuid, string.Format("SendUDP to {0}", ep));

                SocketAsyncEventArgs args = new SocketAsyncEventArgs();
                args.RemoteEndPoint = ep;
                args.SetBuffer(bData, 0, nLength);
                args.Completed += new EventHandler <SocketAsyncEventArgs>(SendUDP_Completed);
                s.SendToAsync(args);
                return(nLength);
            }
        }
 // There's no MiLight controller package yet, so let's just inline the
 // socket code here...
 private void Send(byte[] command)
 {
     // We should be able to use UdpClient. Gah.
     using (var socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp))
     {
         var args = new SocketAsyncEventArgs { RemoteEndPoint = endPoint };
         args.SetBuffer(command, 0, command.Length);
         using (var done = new ManualResetEvent(false))
         {
             args.Completed += (sender, e) => done.Set();
             if (!socket.SendToAsync(args))
             {
                 throw new Exception("Failed to send to lighting host");
             }
             if (!done.WaitOne(TimeSpan.FromSeconds(5)))
             {
                 throw new Exception("Timed out sending to lighting host");
             }
         }
     }
 }
Beispiel #7
0
        private async Task<PingReply> SendIcmpEchoRequestOverRawSocket(IPAddress address, byte[] buffer, int timeout, PingOptions options)
        {
            EndPoint endPoint = new IPEndPoint(address, 0);

            bool isIpv4 = address.AddressFamily == AddressFamily.InterNetwork;
            ProtocolType protocolType = isIpv4 ? ProtocolType.Icmp : ProtocolType.IcmpV6;
            // Use the current thread's ID as the identifier.
            ushort identifier = (ushort)Environment.CurrentManagedThreadId;
            IcmpHeader header = new IcmpHeader()
            {
                Type = isIpv4 ? (byte)IcmpV4MessageType.EchoRequest : (byte)IcmpV6MessageType.EchoRequest,
                Code = 0,
                HeaderChecksum = 0,
                Identifier = identifier,
                SequenceNumber = 0,
            };

            byte[] sendBuffer = CreateSendMessageBuffer(header, buffer);

            using (Socket socket = new Socket(address.AddressFamily, SocketType.Raw, protocolType))
            {
                socket.ReceiveTimeout = timeout;
                socket.SendTimeout = timeout;
                // Setting Socket.DontFragment and .Ttl is not supported on Unix, so ignore the PingOptions parameter.

                int ipHeaderLength = isIpv4 ? IpHeaderLengthInBytes : 0;
                await socket.SendToAsync(new ArraySegment<byte>(sendBuffer), SocketFlags.None, endPoint).ConfigureAwait(false);
                byte[] receiveBuffer = new byte[ipHeaderLength + IcmpHeaderLengthInBytes + buffer.Length];

                long elapsed;
                Stopwatch sw = Stopwatch.StartNew();
                // Read from the socket in a loop. We may receive messages that are not echo replies, or that are not in response
                // to the echo request we just sent. We need to filter such messages out, and continue reading until our timeout.
                // For example, when pinging the local host, we need to filter out our own echo requests that the socket reads.
                while ((elapsed = sw.ElapsedMilliseconds) < timeout)
                {
                    Task<SocketReceiveFromResult> receiveTask = socket.ReceiveFromAsync(
                                                                    new ArraySegment<byte>(receiveBuffer),
                                                                    SocketFlags.None,
                                                                    endPoint);
                    var cts = new CancellationTokenSource();
                    Task finished = await Task.WhenAny(receiveTask, Task.Delay(timeout - (int)elapsed, cts.Token)).ConfigureAwait(false);
                    cts.Cancel();
                    if (finished != receiveTask)
                    {
                        sw.Stop();
                        return CreateTimedOutPingReply();
                    }

                    SocketReceiveFromResult receiveResult = receiveTask.GetAwaiter().GetResult();
                    int bytesReceived = receiveResult.ReceivedBytes;
                    if (bytesReceived - ipHeaderLength < IcmpHeaderLengthInBytes)
                    {
                        continue; // Not enough bytes to reconstruct IP header + ICMP header.
                    }

                    byte type, code;
                    unsafe
                    {
                        fixed (byte* bytesPtr = receiveBuffer)
                        {
                            int icmpHeaderOffset = ipHeaderLength;
                            IcmpHeader receivedHeader = *((IcmpHeader*)(bytesPtr + icmpHeaderOffset)); // Skip IP header.
                            type = receivedHeader.Type;
                            code = receivedHeader.Code;

                            if (identifier != receivedHeader.Identifier
                                || type == (byte)IcmpV4MessageType.EchoRequest
                                || type == (byte)IcmpV6MessageType.EchoRequest) // Echo Request, ignore
                            {
                                continue;
                            }
                        }
                    }

                    sw.Stop();
                    long roundTripTime = sw.ElapsedMilliseconds;
                    int dataOffset = ipHeaderLength + IcmpHeaderLengthInBytes;
                    // We want to return a buffer with the actual data we sent out, not including the header data.
                    byte[] dataBuffer = new byte[bytesReceived - dataOffset];
                    Array.Copy(receiveBuffer, dataOffset, dataBuffer, 0, dataBuffer.Length);

                    IPStatus status = isIpv4
                                        ? IcmpV4MessageConstants.MapV4TypeToIPStatus(type, code)
                                        : IcmpV6MessageConstants.MapV6TypeToIPStatus(type, code);

                    return new PingReply(address, options, status, roundTripTime, dataBuffer);
                }

                // We have exceeded our timeout duration, and no reply has been received.
                sw.Stop();
                return CreateTimedOutPingReply();
            }
        }
        internal static int SendUdp(Socket s, byte[] msg, int len, IPEndPoint EP)
        {
            string response = "Operation Timeout";
            int sent = 0;

            if (s != null)
            {
                // Create SocketAsyncEventArgs context object
                SocketAsyncEventArgs socketEventArg = new SocketAsyncEventArgs();

                // Set properties on context object
                socketEventArg.RemoteEndPoint = EP;

                // Inline event handler for the Completed event.
                // Note: This event handler was implemented inline in order to make this method self-contained.
                socketEventArg.Completed += new EventHandler<SocketAsyncEventArgs>(delegate(object ss, SocketAsyncEventArgs e)
                {
                    response = e.SocketError.ToString();
                    sent = e.BytesTransferred;
                    // Unblock the UI thread
                    try
                    {
                        _clientDone[s].Set();
                    }
                    catch (KeyNotFoundException)
                    {
                    }
                });

                // Add the data to be sent into the buffer
                socketEventArg.SetBuffer(msg, 0, len);

                // Sets the state of the event to nonsignaled, causing threads to block
                _clientDone[s].Reset();

                // Make an asynchronous Send request over the socket
                if (s.SendToAsync(socketEventArg) == false)
                {
                    response = socketEventArg.SocketError.ToString();
                    sent = socketEventArg.BytesTransferred;
                    // Unblock the UI thread
                    try
                    {
                        _clientDone[s].Set();
                    }
                    catch (KeyNotFoundException)
                    {
                    }
                }

                // Block the UI thread for a maximum of TIMEOUT_MILLISECONDS milliseconds.
                // If no response comes back within this time then proceed
                _clientDone[s].WaitOne(TimeOut);
            }
            return sent;
        }
 public static Task <int> SendToAsync(this Socket socket, ArraySegment <byte> buffer, SocketFlags socketFlags, EndPoint remoteEP) =>
 socket.SendToAsync(buffer, socketFlags, remoteEP);
Beispiel #10
0
 public void DeterminePort(AsyncCallback callback)
 {
     if (PortDetermined)
         return;
     acb = new AsyncCallback(callback);
     RtpEvntArgs.RemoteEndPoint = new IPEndPoint(IPAddress.Parse(PortDetermineServerAddress), PortDetermineServerPort);
     var send_buffer = Encoding.UTF8.GetBytes("Connect;LoopBack;");
     RtpEvntArgs.SetBuffer(send_buffer, 0, send_buffer.Length);
     CurrentState = RtpState.DeterminePort;
     try
     {
         RtpSocket.SendToAsync(RtpEvntArgs);
     }
     catch (ObjectDisposedException)
     {
         RtpSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
         RtpSocket.SendToAsync(RtpEvntArgs);
     }
 }
Beispiel #11
0
        /// <summary>
        /// Gets if IO completion ports supported by OS.
        /// </summary>
        /// <returns></returns>
        public static bool IsIoCompletionPortsSupported()
        {
            Socket s = new Socket(AddressFamily.InterNetwork,SocketType.Dgram,ProtocolType.Udp);
            try{
                SocketAsyncEventArgs e = new SocketAsyncEventArgs();
                e.SetBuffer(new byte[0],0,0);
                e.RemoteEndPoint = new IPEndPoint(IPAddress.Loopback,111);
                s.SendToAsync(e);

                return true;
            }
            catch(NotSupportedException nX){
                string dummy = nX.Message;

                return false;
            }
            finally{
                s.Close();
            }
        }
        //
        // Send a command over UDP
        //
        public static void SendUDP(object sender, DoWorkEventArgs ea)
        {
            const int MAX_RECVBUFFER_SIZE = 2048;

            // Create a new socket instance
            // Since this socket is only used within the WiFi network, the preference is on the NonCellular side,
            // to not send the UDP broadcast into the Internet, it wouldn't be delivered...
            Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            socket.SetNetworkPreference(NetworkSelectionCharacteristics.NonCellular);
            SocketAsyncEventArgs socketEventArg = new SocketAsyncEventArgs();

            // Let's assume that the local network broadcast address can be created by changing the last digit to 255
            // - Like 192.168.0.xx -> 192.168.0.255
            // WP8 does support sending to IPAddress.Broadcast, i.e. "255.255.255.255", but there's something
            // wrong with the socket handling:
            // - Cannot use 'SendToAsync', but have to use 'ConnectAsync' instead
            // - Cannot receive any data using the same socket (code seems OK, but nothing is received)
            byte[] localBroadcastAddressBytes = FindMyIPAddress().GetAddressBytes();
            localBroadcastAddressBytes[3] = 255;
            IPAddress localBroadcast = new IPAddress(localBroadcastAddressBytes);

            socketEventArg.RemoteEndPoint = new IPEndPoint(localBroadcast, UDPPort);
            socketEventArg.Completed += new EventHandler<SocketAsyncEventArgs>(delegate(object s, SocketAsyncEventArgs e)
            {
                switch (e.LastOperation)
                {
                    case SocketAsyncOperation.SendTo: // The broadcast was sent successfully, now start listening on the same socket
                        Socket sock = e.UserToken as Socket;
                        socketEventArg.SetBuffer(new Byte[MAX_RECVBUFFER_SIZE], 0, MAX_RECVBUFFER_SIZE);
                        sock.ReceiveFromAsync(socketEventArg);
                        break;

                    case SocketAsyncOperation.ReceiveFrom: // Received a response to the broadcast
                        if (e.SocketError == System.Net.Sockets.SocketError.Success)
                        {
                            // Retrieve the data from the buffer
                            var response = Encoding.UTF8.GetString(e.Buffer, e.Offset, e.BytesTransferred);
                            response = response.Trim('\0');

                            System.Diagnostics.Debug.WriteLine("Received JSON data: " + response);

                            // Is this is an 'identify' or 'command' response?
                            HeatPumpIdentifyResponse identifyResponse = (HeatPumpIdentifyResponse)JsonFunctions.DeserializeFromStringToJson(response, typeof(HeatPumpIdentifyResponse));
                            System.Diagnostics.Debug.WriteLine("Response to command: " + identifyResponse.command + ": " + response);

                            // Run the notification handler (if found)
                            if (App.ViewModel.notificationHandlers.ContainsKey(identifyResponse.command))
                            {
                                System.Diagnostics.Debug.WriteLine("Found handler for command " + identifyResponse.command);
                                App.ViewModel.notificationHandlers[identifyResponse.command](response);
                            }
                        }
                        break;
                }
            });

            // Add the data to be sent into the send buffer
            byte[] payload = Encoding.UTF8.GetBytes((string)ea.Argument);
            socketEventArg.SetBuffer(payload, 0, payload.Length);

            // Add the socket as the UserToken for use within the event handler
            socketEventArg.UserToken = socket;

            // Send the UDP broadcast
            socket.SendToAsync(socketEventArg);
        }
        private async void Search(string st, TimeSpan? timeout = null)
        {
            Log("Search");

            var ssdp_data = new StringBuilder()
                .Append("M-SEARCH * HTTP/1.1").Append("\r\n")
                .Append("HOST: ").Append(MULTICAST_ADDRESS).Append(":").Append(SSDP_PORT.ToString()).Append("\r\n")
                .Append("MAN: ").Append("\"ssdp:discover\"").Append("\r\n")
                .Append("MX: ").Append(MX.ToString()).Append("\r\n")
                .Append("ST: ").Append(st).Append("\r\n")
                .Append("\r\n")
                .ToString();
            var data_byte = Encoding.UTF8.GetBytes(ssdp_data);

            var timeout_called = false;

#if WINDOWS_PHONE||DOT_NET
            var DD_Handler = new AsyncCallback(ar =>
            {
                if (timeout_called)
                {
                    return;
                }

                var req = ar.AsyncState as HttpWebRequest;

                try
                {
                    var res = req.EndGetResponse(ar) as HttpWebResponse;
                    using (var reader = new StreamReader(res.GetResponseStream(), Encoding.UTF8))
                    {
                        try
                        {
                            var response = reader.ReadToEnd();
                            OnDiscovered(new DeviceDescriptionEventArgs(response));

                            var camera = AnalyzeDescription(response);
                            if (camera != null)
                            {
                                OnDiscovered(new SonyCameraDeviceEventArgs(camera, req.RequestUri));
                            }
                        }
                        catch (Exception)
                        {
                            Log("Invalid XML");
                            //Invalid XML.
                        }
                    }
                }
                catch (WebException)
                {
                    //Invalid DD location or network error.
                }
            });
            var socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            socket.SendBufferSize = data_byte.Length;

            var snd_event_args = new SocketAsyncEventArgs();
            snd_event_args.RemoteEndPoint = new IPEndPoint(IPAddress.Parse(MULTICAST_ADDRESS), SSDP_PORT);
            snd_event_args.SetBuffer(data_byte, 0, data_byte.Length);

            var rcv_event_args = new SocketAsyncEventArgs();
            rcv_event_args.SetBuffer(new byte[RESULT_BUFFER], 0, RESULT_BUFFER);

            var SND_Handler = new EventHandler<SocketAsyncEventArgs>((sender, e) =>
            {
                if (e.SocketError == SocketError.Success && e.LastOperation == SocketAsyncOperation.SendTo)
                {
                    try
                    {
                        socket.ReceiveBufferSize = RESULT_BUFFER;
                        socket.ReceiveAsync(rcv_event_args);
                    }
                    catch (ObjectDisposedException)
                    {
                        Log("Socket is already disposed.");
                    }
                }
            });
            snd_event_args.Completed += SND_Handler;

            var RCV_Handler = new EventHandler<SocketAsyncEventArgs>((sender, e) =>
            {
                if (e.SocketError == SocketError.Success && e.LastOperation == SocketAsyncOperation.Receive)
                {
                    string result = Encoding.UTF8.GetString(e.Buffer, 0, e.BytesTransferred);
                    //Log(result);

                    GetDeviceDescriptionAsync(DD_Handler, result);

                    try
                    {
                        socket.ReceiveAsync(e);
                    }
                    catch (ObjectDisposedException)
                    {
                        Log("Socket is already disposed.");
                    }
                }
            });
            rcv_event_args.Completed += RCV_Handler;
            socket.SendToAsync(snd_event_args);
#elif WINDOWS_PHONE_APP||WINDOWS_APP||NETFX_CORE
            var handler = new TypedEventHandler<DatagramSocket, DatagramSocketMessageReceivedEventArgs>(async (sender, args) =>
            {
                Log("Datagram message received");
                if (timeout_called || args == null)
                {
                    return;
                }
                string data;
                using (var reader = args.GetDataReader())
                {
                    data = reader.ReadString(reader.UnconsumedBufferLength);
                }
                Log(data);
                await GetDeviceDescriptionAsync(data, args.LocalAddress).ConfigureAwait(false);
            });

            var adapters = await GetActiveAdaptersAsync().ConfigureAwait(false);

            await Task.WhenAll(adapters.Select(async adapter =>
            {
                using (var socket = new DatagramSocket())
                {
                    socket.Control.DontFragment = true;
                    socket.MessageReceived += handler;

                    try
                    {
                        await socket.BindServiceNameAsync("", adapter);
                        socket.JoinMulticastGroup(MULTICAST_HOST);

                        using (var output = await socket.GetOutputStreamAsync(MULTICAST_HOST, SSDP_PORT.ToString()))
                        {
                            using (var writer = new DataWriter(output))
                            {
                                writer.WriteBytes(data_byte);
                                await writer.StoreAsync();
                            }
                        }
                        await Task.Delay((timeout == null) ? DEFAULT_TIMEOUT : timeout.Value).ConfigureAwait(false);
                        Log("Search Timeout");
                        timeout_called = true;
                    }
                    catch (Exception e)
                    {
                        Log("Failed to send multicast: " + e.StackTrace);
                    }
                    finally
                    {
                        socket.MessageReceived -= handler;
                    }
                }
            })).ConfigureAwait(false);
#endif
#if WINDOWS_PHONE||DOT_NET
            await Task.Delay((timeout == null) ? DEFAULT_TIMEOUT : timeout.Value).ConfigureAwait(false);

            Log("Search Timeout");
            timeout_called = true;
            snd_event_args.Completed -= SND_Handler;
            rcv_event_args.Completed -= RCV_Handler;
            socket.Close();
#endif
            OnTimeout(new EventArgs());
        }
Beispiel #14
0
        /// <summary>
        /// Search devices and retrieve their device info.
        /// </summary>
        /// <param name="timeoutSec">Seconds to wait before invokation of OnTimeout.</param>
        /// <param name="OnServerFound">Success callback. This will be invoked for each devices until OnTimeout is invoked.</param>
        /// <param name="OnTimeout">Timeout callback.</param>
        public async void SearchDevices(int timeoutSec, Action<DeviceInfo> OnServerFound, Action OnTimeout)
        {
            if (OnServerFound == null || OnTimeout == null)
            {
                throw new ArgumentNullException();
            }

            Debug.WriteLine("DeviceFinder.SearchDevices");

            if (timeoutSec < 2)
            {
                timeoutSec = 2;
            }

            const int MX = 1;

            var ssdp_data = new StringBuilder()
                .Append("M-SEARCH * HTTP/1.1").Append("\r\n")
                .Append("HOST: ").Append(multicast_address).Append(":").Append(ssdp_port.ToString()).Append("\r\n")
                .Append("MAN: ").Append("\"ssdp:discover\"").Append("\r\n")
                .Append("MX: ").Append(MX.ToString()).Append("\r\n")
                .Append("ST: urn:schemas-sony-com:service:ScalarWebAPI:1").Append("\r\n")
                //.Append("ST: ssdp:all").Append("\r\n") // For debug
                .Append("\r\n")
                .ToString();
            byte[] data_byte = Encoding.UTF8.GetBytes(ssdp_data);
            //Debug.WriteLine(ssdp_data);

            bool timeout_called = false;

            var DD_Handler = new AsyncCallback(ar =>
            {
                if (timeout_called)
                {
                    return;
                }

                var req = ar.AsyncState as HttpWebRequest;

                try
                {
                    var res = req.EndGetResponse(ar) as HttpWebResponse;
                    using (var reader = new StreamReader(res.GetResponseStream(), Encoding.UTF8))
                    {
                        try
                        {
                            var info = AnalyzeDD(reader.ReadToEnd());
                            NotifyFoundAsync(info, OnServerFound);
                        }
                        catch (Exception)
                        {
                            //Invalid XML.
                        }
                    }
                }
                catch (WebException)
                {
                    //Invalid DD location or network error.
                }
            });

#if WINDOWS_PHONE
            Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            socket.SendBufferSize = data_byte.Length;

            SocketAsyncEventArgs snd_event_args = new SocketAsyncEventArgs();
            snd_event_args.RemoteEndPoint = new IPEndPoint(IPAddress.Parse(multicast_address), ssdp_port);
            snd_event_args.SetBuffer(data_byte, 0, data_byte.Length);

            SocketAsyncEventArgs rcv_event_args = new SocketAsyncEventArgs();
            rcv_event_args.SetBuffer(new byte[result_buffer], 0, result_buffer);

            var SND_Handler = new EventHandler<SocketAsyncEventArgs>((sender, e) =>
            {
                if (e.SocketError == SocketError.Success && e.LastOperation == SocketAsyncOperation.SendTo)
                {
                    socket.ReceiveBufferSize = result_buffer;
                    socket.ReceiveAsync(rcv_event_args);
                }
            });
            snd_event_args.Completed += SND_Handler;

            var RCV_Handler = new EventHandler<SocketAsyncEventArgs>((sender, e) =>
            {
                if (e.SocketError == SocketError.Success && e.LastOperation == SocketAsyncOperation.Receive)
                {
                    string result = Encoding.UTF8.GetString(e.Buffer, 0, e.BytesTransferred);
                    //Debug.WriteLine(result);

                    GetDDAsync(DD_Handler, result);

                    socket.ReceiveAsync(e);
                }
            });
            rcv_event_args.Completed += RCV_Handler;
            socket.SendToAsync(snd_event_args);
#elif NETFX_CORE
            var sock = new DatagramSocket();
            sock.MessageReceived += (sender, args) =>
            {
                if (timeout_called || args == null)
                {
                    return;
                }
                var reader = args.GetDataReader();
                string data = reader.ReadString(reader.UnconsumedBufferLength);
                Debug.WriteLine(data);

                GetDDAsync(DD_Handler, data);
            };
            try
            {
                await sock.BindServiceNameAsync(ssdp_port.ToString());
            }
            catch (Exception)
            {
                Debug.WriteLine("Duplicate search is not supported");
                return;
            }
            var host = new HostName(multicast_address);
            sock.JoinMulticastGroup(host);
            try
            {
                var output = await sock.GetOutputStreamAsync(host, ssdp_port.ToString());
                await output.WriteAsync(data_byte.AsBuffer());
                await sock.OutputStream.FlushAsync();
            }
            catch (Exception)
            {
                Debug.WriteLine("Failed to send multicast");
                return;
            }
#endif

            await RunTimeoutInvokerAsync(timeoutSec, () =>
            {
                Debug.WriteLine("SSDP Timeout");
                timeout_called = true;
#if WINDOWS_PHONE
                snd_event_args.Completed -= SND_Handler;
                rcv_event_args.Completed -= RCV_Handler;
                socket.Close();
#elif NETFX_CORE
                sock.Dispose();
#endif
                OnTimeout.Invoke();
            });
        }
Beispiel #15
0
        protected override void Discover(Socket client, CancellationToken cancelationToken)
        {
            NextSearch = DateTime.UtcNow.AddSeconds(1);
            var searchEndpoint = new IPEndPoint(
                WellKnownConstants.IPv4MulticastAddress
                /*IPAddress.Broadcast*/
                , 1900);

            foreach (var serviceType in ServiceTypes)
            {
                var datax = DiscoverDeviceMessage.Encode(serviceType);
                var data = Encoding.ASCII.GetBytes(datax);

                // UDP is unreliable, so send 3 requests at a time (per Upnp spec, sec 1.1.2)
                // Yes, however it works perfectly well with just 1 request.
                for (var i = 0; i < 2; i++)
                {
                    if (cancelationToken.IsCancellationRequested) return;
                    var args = new SocketAsyncEventArgs {RemoteEndPoint = searchEndpoint};
                    args.SetBuffer(data, 0, data.Length);
                    client.SendToAsync(args);
                }
            }
        }
 private bool SentWorker( Socket s, SocketAsyncEventArgs b )
 {
     var index = (int) b.UserToken;
     var isStream = s.SocketType == SocketType.Stream;
     if (isStream){
         while (
         this._isAttacking
         && this._sendLast[ index ]-- > 0
         && ( b.SocketError == SocketError.Success && s.Connected ) )
         try {
             //this.RefreshSendData( index );
             if ( s.SendAsync( this._sendArgs[ index ] ) ) return true;
         }
         catch { }
     }
     else {
         while ( this._isAttacking ) {
             try {
                 if ( s.SendToAsync( this._sendArgs[ index ] ) ) return true; //prevent stack overflow
             }
             catch { }
         }
     }
     return !this._isAttacking && b.SocketError == SocketError.Success;
 }
Beispiel #17
0
 bool Utils.Wrappers.Interfaces.ISocket.SendToAsync(SocketAsyncEventArgs e)
 {
     return(InternalSocket.SendToAsync(e));
 }
Beispiel #18
0
        public void StartSearch()
        {
            if (state == SearchState.Searching)
                this.StopSearch(SearchStoppedReason.Aborted);

            searchSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            var args = CreateSearchEventArgs();
            searchSocket.SendToAsync(args);

            retryTimer = new Timer(new TimerCallback(SearchRetry), null, TimeSpan.FromSeconds(searchRetrySeconds), TimeSpan.FromSeconds(searchRetrySeconds));
            timeoutTimer = new Timer(new TimerCallback(SearchTimeout), null, TimeSpan.FromSeconds(searchTimeoutSeconds), TimeSpan.FromMilliseconds(-1));
            state = SearchState.Searching;
        }