コード例 #1
0
    private async void InitConnection()
    {
        print("Initializing socket...");

        _socket = new DatagramSocket();
        _socket.Control.MulticastOnly = true;
        _socket.MessageReceived      += Socket_MessageReceived;

        print("Listening enabled!");

        await _socket.BindServiceNameAsync(_multicastPort);

        _socket.JoinMulticastGroup(new HostName(_multicastAddress));
        outputStream = await _socket.GetOutputStreamAsync(new HostName(_multicastAddress), _multicastPort);

        writer = new DataWriter(outputStream);

        print("Socket initialized!");

        MulticastAsync("This is a TestMessage");

        print("Test message sent!");
    }
コード例 #2
0
        public static async void switchOn(String severip)
        {
            DatagramSocket datagramSocket = null;

            try
            {
                HostName hostName = new HostName(severip);
                datagramSocket = new DatagramSocket();

                IOutputStream outputStream = await datagramSocket.GetOutputStreamAsync(hostName, QUIC_PORT);

                DataWriter writer = new DataWriter(outputStream);
                writer.WriteBytes(ON_SWITCH_BYTES);
                await writer.StoreAsync();

                isSwitchOn = true;
            }
            catch (Exception exception)
            {
                datagramSocket.Dispose();
                datagramSocket = null;
            }
        }
コード例 #3
0
        //Event Fires Off when a message is received on that Socket
        private async void MessageReceived(DatagramSocket socket, DatagramSocketMessageReceivedEventArgs eventArguments)
        {
            //IF Robot is not Running
            //Msg recived every 10 sec
            if (!_IsRobotRunning)
            {
                try
                {
                    IOutputStream outputStream = await socket.GetOutputStreamAsync(
                        eventArguments.RemoteAddress,
                        eventArguments.RemotePort);

                    UpdateUi("Found Ev3! Attempting To Connect!");

                    //Pass the Remote IP address into the brick init method to get a connection
                    BrickInit(eventArguments.RemoteAddress);
                }
                catch (Exception)
                {
                    UpdateUi("Oops Something Went Wrong \nCouldnt Connect to the Ev3 Brick");
                }
            }
        }
コード例 #4
0
        private async Task <bool> OpenAsync()
        {
            bool result = false;

            try
            {
                if (writer == null)
                {
                    var hostname = new HostName(SERVERHOST);
                    socket?.Dispose();
                    socket = new DatagramSocket();
                    var port = (ushort)Port.internal_syslog;
                    stream = (await socket.GetOutputStreamAsync(hostname, port.ToString())).AsStreamForWrite();
                    writer = new StreamWriter(stream);
                    result = true;
                }
            }
            catch (Exception)
            {
                Dispose();
            }
            return(result);
        }
コード例 #5
0
        private static async Task BindToSocketAndWriteQuery(DatagramSocket socket, byte[] bytes, CancellationToken cancellationToken)
        {
            await socket.BindServiceNameAsync("5353")
            .AsTask(cancellationToken)
            .ConfigureAwait(false);

            socket.JoinMulticastGroup(new HostName("224.0.0.251"));
            var os = await socket.GetOutputStreamAsync(new HostName("224.0.0.251"), "5353")
                     .AsTask(cancellationToken)
                     .ConfigureAwait(false);

            using (var writer = new DataWriter(os))
            {
                writer.WriteBytes(bytes);
                await writer.StoreAsync()
                .AsTask(cancellationToken)
                .ConfigureAwait(false);

                Debug.WriteLine("Sent mDNS query");

                writer.DetachStream();
            }
        }
コード例 #6
0
        private async void _socketUdp_MessageReceived(DatagramSocket sender, DatagramSocketMessageReceivedEventArgs args)
        {
            try
            {
                uint   stringLength    = args.GetDataReader().UnconsumedBufferLength;
                string receivedMessage = args.GetDataReader().ReadString(stringLength);

                if (receivedMessage.ToLower().Equals(CommunicationCommands.MCCConnection.ToLower()))
                {
                    IOutputStream outputStream = await _socketUdp.GetOutputStreamAsync(
                        args.RemoteAddress,
                        args.RemotePort);

                    MCCConnection = new ConnectionInfo(args.RemoteAddress.ToString(), args.RemotePort, outputStream);
                }

                MessageReceived?.Invoke(this, new CommunicationMsg(receivedMessage));
            }
            catch (Exception ex)
            {
                string error = ex.Message;
            }
        }
コード例 #7
0
        public async void Broadcast(TorrentManager manager)
        {
            if (manager.HasMetadata && manager.Torrent.IsPrivate)
            {
                return;
            }

            var message =
                string.Format(
                    "BT-SEARCH * HTTP/1.1\r\nHost: 239.192.152.143:6771\r\nPort: {0}\r\nInfohash: {1}\r\n\r\n\r\n",
                    manager.Engine.Settings.ListenPort, manager.InfoHash.ToHex());
            var data = Encoding.ASCII.GetBytes(message);

            try
            {
                var output = await _socket.GetOutputStreamAsync(_hostName, Port);

                await output.WriteAsync(data.AsBuffer());
            }
            catch
            {
                // If data can't be sent, just ignore the error
            }
        }
コード例 #8
0
ファイル: NetSocket.cs プロジェクト: achooley/LiteNetLib
        public int SendTo(byte[] data, NetEndPoint remoteEndPoint, ref int errorCode)
        {
            try
            {
                DataWriter writer;
                if (!_peers.TryGetValue(remoteEndPoint, out writer))
                {
                    var outputStream =
                        _datagramSocket.GetOutputStreamAsync(remoteEndPoint.HostName, remoteEndPoint.PortStr)
                        .AsTask()
                        .Result;
                    writer = new DataWriter(outputStream);
                    _peers.Add(remoteEndPoint, writer);
                }

                writer.WriteBytes(data);
                var res = writer.StoreAsync().AsTask().Result;
                return((int)res);
            }
            catch (Exception)
            {
                return(-1);
            }
        }
コード例 #9
0
        private async void SendMessage(SensorReading newSensorReading)
        {
            try
            {
                _timer.Stop();

                var socket = new DatagramSocket();

                var message = BuildMessage(newSensorReading);

                using (var stream = await socket.GetOutputStreamAsync(new HostName(_ipAddress), _port))
                {
                    await stream.WriteAsync(message.AsBuffer());

                    await stream.FlushAsync();
                }

                _timer.Start();
            }
            catch (Exception ex)
            {
                ExceptionEvent(ex);
            }
        }
コード例 #10
0
        public static void AcceptClient(DatagramSocket listener, DatagramSocketMessageReceivedEventArgs args)
        {
            new Task(async() =>
            {
                // Retrieve client IP info
                byte[] serverIPBytes = CryptographicBuffer.ConvertStringToBinary(serverIP, BinaryStringEncoding.Utf8).ToArray();
                //HostName clientIP = args.RemoteAddress;
                //string clientPort = args.RemotePort;
                DataReader reader   = args.GetDataReader();
                uint numBytesLoaded = await reader.LoadAsync(1024);
                //byte[] buffer = new byte[reader.UnconsumedBufferLength];
                //reader.ReadBytes(buffer);

                string clientIP = CryptographicBuffer.ConvertBinaryToString(BinaryStringEncoding.Utf8, reader.ReadBuffer(reader.UnconsumedBufferLength));

                DataWriter writer = new DataWriter(await listener.GetOutputStreamAsync(new HostName(clientIP), Config.Ports.FindServer.ToString()));

                writer.WriteBytes(serverIPBytes);
                await writer.StoreAsync(); // necessary??

                // Reset listening status
                await listener.ConnectAsync(new HostName("0.0.0.0"), Config.Ports.FindServer.ToString());
            }).Start();
        }
コード例 #11
0
    private async void initSockets(string host, int inputPort, int outputPort)
    {
        // input socket
        inputSocket = new DatagramSocket();
        Windows.Networking.HostName serverAddr = new Windows.Networking.HostName(host);
        Stream streamOut = (await inputSocket.GetOutputStreamAsync(serverAddr, "" + inputPort)).AsStreamForWrite();

        inputWriter = new StreamWriter(streamOut);

        // output socket
        outputSocket = new DatagramSocket();
        outputSocket.MessageReceived += Socket_MessageReceived;

        try
        {
            await outputSocket.BindServiceNameAsync("" + outputPort);
        }
        catch (Exception e)
        {
            Debug.Log(e.ToString());
            Debug.Log(Windows.Networking.Sockets.SocketError.GetStatus(e.HResult).ToString());
            return;
        }
    }
コード例 #12
0
        public async Task <bool> Send(string buffer)
        {
            try
            {
                System.Diagnostics.Debug.WriteLine("Message Sent: " + buffer);
                if (msocketSend == null)
                {
                    await InitializeSend();
                }

                HostName   mcast  = new HostName(mAddress);
                DataWriter writer = new DataWriter(await msocketSend.GetOutputStreamAsync(mcast, mPort));

                if (writer != null)
                {
                    writer.WriteString(buffer);
                    uint result = await writer.StoreAsync();

                    bool bresult = await writer.FlushAsync();

                    writer.DetachStream();
                    writer.Dispose();
                    return(true);
                }
            }
            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)
                {
                    return(false);
                }
                return(false);
            }
            return(false);
        }
コード例 #13
0
        /// <summary>
        /// Attempts to send a magic packet to the desination hostname, on the specified port with the specified MAC address.
        /// </summary>
        /// <param name="destination">Destination hostname or IP address.</param>
        /// <param name="destinationPort">Destination port number.</param>
        /// <param name="targetMac">Destination MAC address. Bytes can be separated by colons, dashes, or nothing.</param>
        /// <returns>True if magic packet is sent successfully, false otherwise.</returns>
        public async Task <bool> SendMagicPacket(Windows.Networking.HostName destination, uint destinationPort, string targetMac)
        {
            try
            {
                DatagramSocket _socket = new DatagramSocket();

                using (var stream = await _socket.GetOutputStreamAsync(destination, destinationPort.ToString()))
                {
                    //Split on common MAC separators
                    char?splitChar = null;
                    if (targetMac.Contains('-'))
                    {
                        splitChar = '-';
                    }
                    else if (targetMac.Contains(':'))
                    {
                        splitChar = ':';
                    }
                    else if (targetMac.Contains(' '))
                    {
                        splitChar = ' ';
                    }

                    //Turn MAC into array of bytes
                    byte[] macAsArray;
                    if (splitChar != null)
                    {
                        macAsArray = targetMac.Split((char)splitChar)
                                     .Select(b => Convert.ToByte(b, 16))
                                     .ToArray <byte>();
                    }
                    else
                    {
                        //Jump through MAC-string, reading 2 chars at a time
                        macAsArray = Enumerable.Range(0, targetMac.Length)
                                     .Where(x => x % 2 == 0)
                                     .Select(x => Convert.ToByte(targetMac.Substring(x, 2), 16)) //16 = hexadecimal
                                     .ToArray();
                    }

                    List <byte> magicPacket = new List <byte> {
                        0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF
                    };

                    //A WoLAN magic packet is just FF FF FF FF FF FF, then the target MAC adress repeated 16 times.
                    for (int i = 0; i < 16; i++)
                    {
                        magicPacket = magicPacket.Concat(macAsArray).ToList();
                    }

                    using (DataWriter writer = new DataWriter(stream))
                    {
                        writer.WriteBytes(magicPacket.ToArray <byte>());
                        await writer.StoreAsync();

                        await writer.FlushAsync();

                        return(true);
                    }
                }
            }
            catch (Exception e)
            {
                Debug.WriteLine(e);
                return(false);
            }
        }
コード例 #14
0
        /// <summary>
        /// Send a packet to the specified ipEndPoint. This feature is unique to UDP because of its connectionless structure.
        /// </summary>
        /// <param name="packet">Packet to send</param>
        /// <param name="ipEndPoint">The target ipEndPoint</param>
        private void SendPacketSpecific <packetObjectType>(IPacket packet, IPEndPoint ipEndPoint)
        {
#if FREETRIAL
            if (ipEndPoint.Address == IPAddress.Broadcast)
            {
                throw new NotSupportedException("Unable to send UDP broadcast datagram using this version of NetworkComms.Net. Please purchase a commercial license from www.networkcomms.net which supports UDP broadcast datagrams.");
            }
#endif

            byte[] headerBytes = new byte[0];
            if (ConnectionInfo.ApplicationLayerProtocol == ApplicationLayerProtocolStatus.Enabled)
            {
                long packetSequenceNumber;
                lock (sendLocker)
                {
                    //Set packet sequence number inside sendLocker
                    //Increment the global counter as well to ensure future connections with the same host can not create duplicates
                    Interlocked.Increment(ref NetworkComms.totalPacketSendCount);
                    packetSequenceNumber = packetSequenceCounter++;
                    packet.PacketHeader.SetOption(PacketHeaderLongItems.PacketSequenceNumber, packetSequenceNumber);
                }

                headerBytes = packet.SerialiseHeader(NetworkComms.InternalFixedSendReceiveOptions);
            }
            else
            {
                if (packet.PacketHeader.PacketType != Enum.GetName(typeof(ReservedPacketType), ReservedPacketType.Unmanaged))
                {
                    throw new UnexpectedPacketTypeException("Only 'Unmanaged' packet types can be used if the NetworkComms.Net application layer protocol is disabled.");
                }

                if (packet.PacketData.Length == 0)
                {
                    throw new NotSupportedException("Sending a zero length array if the NetworkComms.Net application layer protocol is disabled is not supported.");
                }
            }

            //We are limited in size for the isolated send
            if (headerBytes.Length + packet.PacketData.Length > maximumSingleDatagramSizeBytes)
            {
                throw new CommunicationException("Attempted to send a UDP packet whose serialised size was " + (headerBytes.Length + packet.PacketData.Length).ToString() + " bytes. The maximum size for a single UDP send is " + maximumSingleDatagramSizeBytes.ToString() + ". Consider using a TCP connection to send this object.");
            }

            if (NetworkComms.LoggingEnabled)
            {
                NetworkComms.Logger.Debug("Sending a UDP packet of type '" + packet.PacketHeader.PacketType + "' from " + ConnectionInfo.LocalIPEndPoint.Address + ":" + ConnectionInfo.LocalIPEndPoint.Port.ToString() + " to " + ipEndPoint.Address + ":" + ipEndPoint.Port.ToString() + " containing " + headerBytes.Length.ToString() + " header bytes and " + packet.PacketData.Length.ToString() + " payload bytes.");
            }

            //Prepare the single byte array to send
            byte[] udpDatagram;
            if (ConnectionInfo.ApplicationLayerProtocol == ApplicationLayerProtocolStatus.Enabled)
            {
                udpDatagram = packet.PacketData.ThreadSafeStream.ToArray(headerBytes.Length);

                //Copy the header bytes into the datagram
                Buffer.BlockCopy(headerBytes, 0, udpDatagram, 0, headerBytes.Length);
            }
            else
            {
                udpDatagram = packet.PacketData.ThreadSafeStream.ToArray();
            }

#if WINDOWS_PHONE || NETFX_CORE
            var getStreamTask = socket.GetOutputStreamAsync(new HostName(ipEndPoint.Address.ToString()), ipEndPoint.Port.ToString()).AsTask();
            getStreamTask.Wait();

            var outputStream = getStreamTask.Result;

            outputStream.WriteAsync(WindowsRuntimeBufferExtensions.AsBuffer(udpDatagram)).AsTask().Wait();
            outputStream.FlushAsync().AsTask().Wait();
#else
            udpClient.Send(udpDatagram, udpDatagram.Length, ipEndPoint);
#endif

            if (NetworkComms.LoggingEnabled)
            {
                NetworkComms.Logger.Trace("Completed send of a UDP packet of type '" + packet.PacketHeader.PacketType + "' from " + ConnectionInfo.LocalIPEndPoint.Address + ":" + ConnectionInfo.LocalIPEndPoint.Port.ToString() + " to " + ipEndPoint.Address + ":" + ipEndPoint.Port.ToString() + ".");
            }
        }
コード例 #15
0
        static async Task BindToSocketAndWriteQuery(DatagramSocket socket, byte[] bytes, CancellationToken cancellationToken)
        {
#if !WINDOWS_PHONE
            try
            {
                // Try to bind using port 5353 first
                var adapter = NetworkInformation.GetInternetConnectionProfile()?.NetworkAdapter;
                if (adapter != null)
                {
                    await socket.BindServiceNameAsync("5353", adapter)
                    .AsTask(cancellationToken)
                    .ConfigureAwait(false);
                }
                else
                {
                    await socket.BindServiceNameAsync("5353")
                    .AsTask(cancellationToken)
                    .ConfigureAwait(false);
                }
            }
            catch (Exception)
            {
                // If it fails, use the default
                var adapter = NetworkInformation.GetInternetConnectionProfile()?.NetworkAdapter;
                if (adapter != null)
                {
                    await socket.BindServiceNameAsync("", adapter)
                    .AsTask(cancellationToken)
                    .ConfigureAwait(false);
                }
                else
                {
                    await socket.BindServiceNameAsync("")
                    .AsTask(cancellationToken)
                    .ConfigureAwait(false);
                }
            }
#else
            try
            {
                await socket.BindServiceNameAsync("5353")
                .AsTask(cancellationToken)
                .ConfigureAwait(false);
            }
            catch (Exception)
            {
                // fallback to "" for WinPhone 10
                await socket.BindServiceNameAsync("")
                .AsTask(cancellationToken)
                .ConfigureAwait(false);
            }
#endif


            socket.JoinMulticastGroup(new HostName("224.0.0.251"));
            var os = await socket.GetOutputStreamAsync(new HostName("224.0.0.251"), "5353")
                     .AsTask(cancellationToken)
                     .ConfigureAwait(false);

            using (var writer = new DataWriter(os))
            {
                writer.WriteBytes(bytes);
                await writer.StoreAsync()
                .AsTask(cancellationToken)
                .ConfigureAwait(false);

                Debug.WriteLine("Sent mDNS query");

                writer.DetachStream();
            }
        }
コード例 #16
0
        public async Task <CharGenResult> WriteUdpAsync(HostName address, string service, string data)
        {
            try
            {
                var haveUdpSocket = EnsureUdpSocket();
                if (haveUdpSocket != null)
                {
                    // Was unable to create the socket.
                    return(haveUdpSocket);
                }

                var stream = await udpSocket.GetOutputStreamAsync(address, service);

                if (string.IsNullOrEmpty(data))
                {
                    // A blank string, when written to a data writer, won't actually result in a
                    // UDP packet being sent. For the special case of not sending any data,
                    // use the WriteAsync on the socket's OutputStream directly.
                    var b = new Windows.Storage.Streams.Buffer(0);
                    await stream.WriteAsync(b);

                    Stats.NWrites++;
                }
                else
                {
                    var dw = new DataWriter(stream);
                    dw.WriteString(data);
                    await dw.StoreAsync();

                    Stats.NWrites++;
                }
                Log(ClientOptions.Verbosity.Verbose, $"Client: UDP: Sent request on local port {udpSocket.Information.LocalPort} request {data}");


                //
                // Wait for an answer
                //
                const int START_DELAY_MS = 10;
                int       currTotalDelay = 0;
                int       currDelay      = START_DELAY_MS;

                CharGenResult udpResult = null;
                while (!UdpResults.TryRemove(udpSocket.Information.LocalPort, out udpResult))
                {
                    await Task.Delay(currDelay);

                    currTotalDelay += currDelay;
                    currDelay       = Math.Min(currDelay * 2, Options.MaxPollLoopInMilliseconds); // Do an exponential backup up to max (10 seconds)
                    if (currTotalDelay >= Options.MaxWaitInMilliseconds)
                    {
                        Log($"ERROR: Client: reply from {address} took too long (outgoing data={data})");
                        var delta = DateTime.UtcNow.Subtract(SocketStartTime).TotalSeconds;
                        udpResult = CharGenResult.MakeFailed(SocketErrorStatus.ConnectionTimedOut, delta);
                        break;
                    }
                }
                return(udpResult);
            }
            catch (Exception ex)
            {
                Stats.NExceptions++;
                Log($"ERROR: Client: Writing {data} to {address} exception {ex.Message}");
                var delta = DateTime.UtcNow.Subtract(SocketStartTime).TotalSeconds;
                return(CharGenResult.MakeFailed(ex, delta));
            }
        }
コード例 #17
0
        /// <summary>
        /// 搜索设备私有函数
        /// </summary>
        /// <param name="timeout">超时时间 毫秒</param>
        /// <returns>Yeelight对象</returns>
        private async static Task <IList <Yeelight> > SearchDeviceHelper(int timeout)
        {
            // 创建Socket
            DatagramSocket udp = new DatagramSocket();
            // 绑定随机端口
            await udp.BindServiceNameAsync("");

            // 获取输出流
            var outputStream = await udp.GetOutputStreamAsync(MULTICAST_HOST, MULTICAST_PORT);

            // Yeelight列表
            Dictionary <string, Yeelight> yeelightList = new Dictionary <string, Yeelight>();

            // 处理回应
            udp.MessageReceived += (sender, args) =>
            {
                // 读取对象
                var reader = args.GetDataReader();
                // 读取设备信息
                string rawDevInfo = reader.ReadString(reader.UnconsumedBufferLength);

                try
                {
                    // 构造Yeelight对象
                    Yeelight device = new Yeelight(rawDevInfo);

                    // 是否已存在
                    if (yeelightList.ContainsKey(device.Id))
                    {
                        // 替换
                        yeelightList[device.Id] = device;
                    }
                    else
                    {
                        // 新增
                        yeelightList.Add(device.Id, device);
                    }
                }
                catch (Exception ex)
                {
                    Debug.WriteLine(ex.ToString());
                }
            };

            // 创建数据写入对象
            using (DataWriter writer = new DataWriter(outputStream))
            {
                // 写入缓冲区
                writer.WriteString(SEARCH_DEVICE_MULTCAST_CONTENT);
                // 发送数据
                await writer.StoreAsync();

                // 分离流
                writer.DetachStream();

                // 等待
                await Task.Delay(timeout);
            }

            // 清理资源
            udp.Dispose();

            return(yeelightList.Values.ToList <Yeelight>());
        }
コード例 #18
0
ファイル: LifxClient.cs プロジェクト: rivy/LifxNet
        private async Task <T> BroadcastMessagePayloadAsync <T>(Windows.Networking.HostName hostName, FrameHeader header, MessageType type, byte[] payload)
            where T : LifxResponse
        {
#if DEBUG
            MemoryStream ms = new MemoryStream();
            await WritePacketToStreamAsync(ms.AsOutputStream(), header, (UInt16)type, payload).ConfigureAwait(false);

            var data = ms.ToArray();
            System.Diagnostics.Debug.WriteLine(
                string.Join(",", (from a in data select a.ToString("X2")).ToArray()));
#endif
            if (hostName == null)
            {
                hostName = new Windows.Networking.HostName("255.255.255.255");
            }
            TaskCompletionSource <T> tcs = null;
            if (//header.AcknowledgeRequired &&
                header.Identifier > 0 &&
                typeof(T) != typeof(UnknownResponse))
            {
                tcs = new TaskCompletionSource <T>();
                Action <LifxResponse> action = (r) =>
                {
                    if (!tcs.Task.IsCompleted)
                    {
                        if (r.GetType() == typeof(T))
                        {
                            tcs.SetResult((T)r);
                        }
                        else
                        {
                        }
                    }
                };
                taskCompletions[header.Identifier] = action;
            }

            using (var stream = await _socket.GetOutputStreamAsync(hostName, Port))
            {
                await WritePacketToStreamAsync(stream, header, (UInt16)type, payload).ConfigureAwait(false);
            }
            T result = default(T);
            if (tcs != null)
            {
                var _ = Task.Delay(1000).ContinueWith((t) =>
                {
                    if (!t.IsCompleted)
                    {
                        tcs.TrySetException(new TimeoutException());
                    }
                });
                try {
                    result = await tcs.Task.ConfigureAwait(false);
                }
                finally
                {
                    taskCompletions.Remove(header.Identifier);
                }
            }
            return(result);
        }
コード例 #19
0
        private async Task ExecuteDiscoveryTask()
        {
            int repeatTime = EndpointController.REPEAT_DISCOVERY_TASK / 2;

            while (running)
            {
                Debug.WriteLine("#> [DiscoveryCloudletMulticast]: Started Cloudlet Discovery using Multicast UDP");
                retry = 0;

                DatagramSocket socketSent   = null;
                DatagramSocket socketReplay = null;
                try
                {
                    socketSent = new DatagramSocket();
                    await socketSent.BindEndpointAsync(null, string.Empty);

                    socketSent.JoinMulticastGroup(ip);

                    socketReplay = new DatagramSocket();
                    socketReplay.MessageReceived += SocketOnMessageReceived;
                    await socketReplay.BindServiceNameAsync(replyCloudletPort.ToString());

                    using (DataWriter writer = new DataWriter(await socketSent.GetOutputStreamAsync(ip, multicastPort.ToString())))
                    {
                        while (retry < 60 && running)
                        {
                            writer.WriteString("mpos_cloudlet_req");
                            await writer.StoreAsync();

                            await writer.FlushAsync();

                            await Task.Delay(500);

                            retry++;
                        }
                    }
                }
                catch (IOException e)
                {
                    Debug.WriteLine("## [DiscoveryCloudletMulticast]: Any problem with i/o in multicast system!\n" + e.ToString());
                }
                finally
                {
                    socketSent.Dispose();
                    socketReplay.Dispose();

                    socketSent   = null;
                    socketReplay = null;
                }

                if (running)
                {
                    Debug.WriteLine(">> [DiscoveryCloudletMulticast]: Retry Discovery Cloudlet, in " + repeatTime + " ms");
                    await Task.Delay(repeatTime);
                }
                else
                {
                    Debug.WriteLine("#> [DiscoveryCloudletMulticast]: Finished Discovery Cloudlet");
                }
            }
        }
コード例 #20
0
        //This code will work on win phone too
        public override async Task <HashSet <Tuple <Uri, Uri> > > GetDeviceLocations(string schema, Func <string, string, byte[]> createSsdpRequest, Func <byte[], int, Uri> parseSsdpResponse)
        {
            var remoteIp   = new HostName("239.255.255.250");
            var remotePort = "1900"; // standard multicast address+port for SSDP
            var reqbuf     =
                WindowsRuntimeBufferExtensions.AsBuffer(
                    createSsdpRequest(remoteIp.RawName + ":" + remotePort, schema));
            var locations = new HashSet <Tuple <Uri, Uri> >();

            using (var socket = new DatagramSocket())
            {
                socket.MessageReceived += (sender, e) =>
                {
                    if (e.LocalAddress.IPInformation != null && e.LocalAddress.IPInformation.NetworkAdapter.IanaInterfaceType == 24)
                    {
                        return;                                                                                                                 // loopback
                    }
                    // any loopback renderer will also report itself on the actual network, and I don't want to show duplicates
                    using (var reader = e.GetDataReader())
                    {
                        var responsebuf = new Byte[reader.UnconsumedBufferLength - 1];
                        reader.ReadBytes(responsebuf);
                        if (_progress != null)
                        {
                            _progress.Report("Received from " + e.RemoteAddress.DisplayName + ":" + e.RemotePort +
                                             vbCrLf + Encoding.UTF8.GetString(responsebuf, 0, responsebuf.Length));
                        }
                        var location = parseSsdpResponse(responsebuf, responsebuf.Length);
                        if (location != null)
                        {
                            locations.Add(Tuple.Create(location, new Uri("http://" + e.LocalAddress.CanonicalName)));
                        }
                    }
                };

                // CAPABILITY: PrivateNetworks
#if WINDOWS_PHONE_APP
                ConnectionProfile connectionProfile = NetworkInformation.GetInternetConnectionProfile();
                await socket.BindEndpointAsync(null, "");
#else
                ConnectionProfile connectionProfile = NetworkInformation.GetInternetConnectionProfile();
                await socket.BindServiceNameAsync("", connectionProfile.NetworkAdapter);
#endif
                socket.Control.OutboundUnicastHopLimit = 1;
                socket.JoinMulticastGroup(remoteIp); // Alas there's no WinRT equivalent of ReuseAddress

                using (var stream = await socket.GetOutputStreamAsync(new HostName("239.255.255.250"), remotePort))
                {
                    await stream.WriteAsync(reqbuf);

                    await Task.Delay(20);

                    await stream.WriteAsync(reqbuf);

                    await Task.Delay(20);

                    await stream.WriteAsync(reqbuf);
                }


                await Task.Delay(1200);
            }
            return(locations);
        }
コード例 #21
0
        protected async Task <long[]> PingService(bool isTcp, int pingRounds)
        {
            long[] pings = new long[pingRounds];
            watch.Reset();

            if (isTcp)
            {
                streamSocket = new StreamSocket();
                await streamSocket.ConnectAsync(hostName, server.PingTcpPort.ToString());

                DataWriter writer = new DataWriter(streamSocket.OutputStream);
                DataReader reader = new DataReader(streamSocket.InputStream);

                int count = 0;
                for (int i = 0; i < pingRounds; i++)
                {
                    watch.Start();
                    writer.WriteString("pigado" + i);
                    await writer.StoreAsync();

                    await writer.FlushAsync();

                    reader.InputStreamOptions = InputStreamOptions.Partial;
                    await reader.LoadAsync(256);

                    watch.Stop();
                    pings[count++] = watch.ElapsedMilliseconds;
                    watch.Reset();

                    if (halted)
                    {
                        throw new InterruptedException("PingService TCP was aborted externally!");
                    }

                    await Task.Delay(500);
                }

                Array.Sort <long>(pings);
                Close(ref writer);
                Close(ref reader);
                Close(ref streamSocket);
            }
            else
            {
                datagramSocket = new DatagramSocket();

                int count = 0;
                datagramSocket.MessageReceived += delegate(DatagramSocket socket, DatagramSocketMessageReceivedEventArgs args)
                {
                    watch.Stop();
                    pings[count++] = watch.ElapsedMilliseconds;
                    watch.Reset();
                };

                //for receive packets
                string port = server.PingUdpPort.ToString();
                await datagramSocket.BindServiceNameAsync(port);

                using (DataWriter writer = new DataWriter(await datagramSocket.GetOutputStreamAsync(hostName, port)))
                {
                    for (int i = 0; i < pingRounds; i++)
                    {
                        watch.Start();

                        writer.WriteString("pigado" + i);
                        await writer.StoreAsync();

                        await writer.FlushAsync();

                        if (halted)
                        {
                            throw new InterruptedException("PingService UDP was aborted externally!");
                        }

                        await Task.Delay(500);
                    }
                }

                Array.Sort <long>(pings);
                Close(ref datagramSocket);
            }

            return(pings);
        }
コード例 #22
0
        async Task <bool> Send(string ip, string Message)
        {
            try
            {
                if (msocketSend == null)
                {
                    return(false);
                }

                // Add Device Information
                string command = CompanionProtocol.GetCommandFromMessage(Message);
                Dictionary <string, string> parameters = CompanionProtocol.GetParametersFromMessage(Message);
                if (!string.IsNullOrEmpty(command))
                {
                    if (parameters == null)
                    {
                        parameters = new Dictionary <string, string>();
                    }
                    if ((parameters != null) && (!parameters.ContainsKey(CompanionProtocol.parameterIPAddress)) &&
                        (!parameters.ContainsKey(CompanionProtocol.parameterName)) &&
                        (!parameters.ContainsKey(CompanionProtocol.parameterKind)) &&
                        (!parameters.ContainsKey(CompanionProtocol.parameterID)))
                    {
                        parameters.Add(CompanionProtocol.parameterID, LocalCompanionDevice.Id);
                        parameters.Add(CompanionProtocol.parameterIPAddress, LocalCompanionDevice.IPAddress);
                        parameters.Add(CompanionProtocol.parameterKind, LocalCompanionDevice.Kind);
                        parameters.Add(CompanionProtocol.parameterName, LocalCompanionDevice.Name);

                        Message = CompanionProtocol.CreateCommand(command, parameters);
                    }
                }
                HostName mcast;
                string   port;
                if ((string.IsNullOrEmpty(ip)) || (string.Equals(ip, MulticastIPAddress)))
                {
                    port  = MulticastUDPPort.ToString();
                    mcast = new HostName(MulticastIPAddress);
                }
                else
                {
                    port  = UnicastUDPPort.ToString();
                    mcast = new HostName(ip);
                }
                DataWriter writer = new DataWriter(await msocketSend.GetOutputStreamAsync(mcast, port));

                if (writer != null)
                {
                    writer.WriteString(Message);
                    uint result = await writer.StoreAsync();

                    bool bresult = await writer.FlushAsync();

                    writer.DetachStream();
                    writer.Dispose();
                    System.Diagnostics.Debug.WriteLine("Message Sent to: " + mcast.CanonicalName + ":" + port + " content: " + Message);
                    return(true);
                }
            }
            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)
                {
                    return(false);
                }
                return(false);
            }
            return(false);
        }
コード例 #23
0
        public static async Task <List <string> > GetAvaliable(string port)
        {
            var list = new List <string>();

        #if UNITY_EDITOR
            using (var socket = new UdpClient {
                Ttl = 1
            }) {
                var timer = new System.Timers.Timer {
                    AutoReset = false,
                    Interval  = 500
                };

                var str          = Encoding.Default.GetBytes("IP?");
                var ct           = new CancellationTokenSource();
                var eventhandler = new EventWaitHandle(false, EventResetMode.ManualReset);
                timer.Elapsed += (sender, args) => { ct.Cancel(); };

                ct.Token.Register(async() => {
                    while (socket.Available > 0)
                    {
                        var rec = await socket.ReceiveAsync();
                        list.Add(rec.RemoteEndPoint.Address.ToString());
                    }

                    eventhandler.Set();
                });

                await socket.SendAsync(str, str.Length, UniversalTcpServer.Multicast, int.Parse(port));

                timer.Start();
                var t = Task.Run(async() => {
                    while (true)
                    {
                        var rec = await socket.ReceiveAsync();
                        list.Add(rec.RemoteEndPoint.Address.ToString());
                    }
                }, ct.Token);

                eventhandler.WaitOne();
            }
        #elif UNITY_WSA
            using (var socket = new DatagramSocket()) {
                var stream = await socket.GetOutputStreamAsync(new HostName(UniversalTcpServer.Multicast), port);

                Logs.Log($"Getting stream form {UniversalTcpServer.Multicast}:{port}");
                socket.MessageReceived += async(sender, args) => {
                    var reader = new StreamReader(args.GetDataStream().AsStreamForRead());
                    var str    = await reader.ReadToEndAsync();

                    Logs.Log($"{str} from {args.RemoteAddress.RawName}");
                    list.Add(args.RemoteAddress.RawName);
                };

                using (var data = new DataWriter(stream)) {
                    data.WriteString("IP?");
                    var i = await data.StoreAsync();

                    var b = await data.FlushAsync();
                }

                Logs.Log($"Client udp socket: {socket.Information.LocalAddress}:{socket.Information.LocalPort}");
                await Task.Delay(1000);
            }
                #endif
            return(list);
        }
コード例 #24
0
        public async ValueTask Init(ChannelReader <byte[]> outboundChan, ILocalAdapter localAdapter, CancellationToken cancellationToken = default)
        {
            var          destination = localAdapter.Destination;
            IAsyncAction connectTask;
            var          dev = NetworkInformation.GetInternetConnectionProfile().NetworkAdapter;

            switch (destination.TransportProtocol)
            {
            case TransportProtocol.Tcp:
                client = new StreamSocket();
                client.Control.NoDelay = true;
                connectTask            = client.ConnectAsync(new HostName(server), serviceName, SocketProtectionLevel.PlainSocket, dev);
                tcpInputStream         = client.InputStream;
                break;

            case TransportProtocol.Udp:
                cryptor = null;
                // Shadowsocks does not require a handshake for UDP transport
                udpClient = new DatagramSocket();
                // MessageReceived must be subscribed at this point
                udpClient.MessageReceived += UdpClient_MessageReceived;
                await udpClient.BindServiceNameAsync(string.Empty, dev).AsTask(cancellationToken).ConfigureAwait(false);

                udpOutputStream = await udpClient.GetOutputStreamAsync(new HostName(server), serviceName).AsTask(cancellationToken).ConfigureAwait(false);

                return;

            default:
                throw new NotImplementedException("Unknown transport protocol");
            }

            byte[] firstBuf       = Array.Empty <byte>();
            var    firstBufCancel = new CancellationTokenSource(500);

            try
            {
                if (await outboundChan.WaitToReadAsync(firstBufCancel.Token).ConfigureAwait(false))
                {
                    outboundChan.TryRead(out firstBuf);
                }
            }
            catch (OperationCanceledException) { }
            finally
            {
                firstBufCancel.Dispose();
            }
            int firstBufLen       = firstBuf.Length;
            int requestPayloadLen = firstBufLen + destination.Host.Size + 4;
            // Later will be reused to store dec iv
            var requestPayload = sendArrayPool.Rent(Math.Max(requestPayloadLen, (int)cryptor.IvLen));
            var headerLen      = destination.FillSocks5StyleAddress(requestPayload);

            firstBuf.CopyTo(requestPayload.AsSpan(headerLen));
            var encryptedFirstSeg    = sendArrayPool.Rent(requestPayloadLen + 66);       // Reserve space for IV or salt + 2 * tag + size
            var ivLen                = Encrypt(Array.Empty <byte>(), encryptedFirstSeg); // Fill IV/salt first
            var encryptedFirstSegLen = ivLen + Encrypt(requestPayload.AsSpan(0, headerLen + firstBufLen), encryptedFirstSeg.AsSpan((int)ivLen));

            try
            {
                await connectTask.AsTask(cancellationToken).ConfigureAwait(false);
            }
            catch (Exception)
            {
                sendArrayPool.Return(requestPayload);
                sendArrayPool.Return(encryptedFirstSeg, true);
                throw;
            }
            try
            {
                // Recv iv first, then GetRecvBufSizeHint will not bother with iv stuff
                receiveIvTask = ReceiveIv(requestPayload, cancellationToken);
                _             = client.OutputStream.WriteAsync(encryptedFirstSeg.AsBuffer(0, (int)encryptedFirstSegLen)).AsTask(cancellationToken);
            }
            finally
            {
                sendArrayPool.Return(encryptedFirstSeg, true);
            }
        }
コード例 #25
0
ファイル: BridgeConnection.cs プロジェクト: eymike/HueControl
        public async Task DiscoverBridge(TimeSpan timeOut)
        {
            var multicastIP = new HostName("239.255.255.250");
            var foundBridge = false;

            using (var socket = new DatagramSocket())
            {
                socket.MessageReceived += async(sender, args) =>
                {
                    var reader         = args.GetDataReader();
                    var bytesRemaining = reader.UnconsumedBufferLength;
                    foreach (var line in reader.ReadString(bytesRemaining).Split(new String[1] {
                        "\r\n"
                    }, StringSplitOptions.RemoveEmptyEntries))
                    {
                        if (line.StartsWith("LOCATION"))
                        {
                            var address = line.Split(new char[1] {
                                ':'
                            }, 2)[1];
                            var message = await _client.GetAsync(address);

                            if (message.IsSuccessStatusCode)
                            {
                                var messageContent = await message.Content.ReadAsStringAsync();

                                var buffer = Encoding.UTF8.GetBytes(messageContent);
                            }
                        }
                    }

                    foundBridge = true;
                };

                await socket.BindEndpointAsync(null, string.Empty);

                socket.JoinMulticastGroup(multicastIP);

                while (true)
                {
                    foundBridge = false;

                    using (var stream = await socket.GetOutputStreamAsync(multicastIP, "1900"))
                        using (var writer = new DataWriter(stream))
                        {
                            var request = new StringBuilder();
                            request.AppendLine("M-SEARCH * HTTP/1.1");
                            request.AppendLine("HOST: 239.255.255.250:1900");
                            request.AppendLine("MAN: ssdp:discover");
                            request.AppendLine("MX: 3");
                            request.AppendLine("ST: ssdp:all");

                            writer.WriteString(request.ToString());
                            await writer.StoreAsync();

                            if (timeOut > TimeSpan.Zero)
                            {
                                await Task.Delay(timeOut);
                            }

                            if (foundBridge)
                            {
                                break;
                            }
                        }
                }
            }
        }
コード例 #26
0
ファイル: Server.cs プロジェクト: DeltaFXD/2DGame
        async void MessageReceived(DatagramSocket sender, DatagramSocketMessageReceivedEventArgs args)
        {
            using (DataReader dataReader = args.GetDataReader())
            {
                dataReader.ByteOrder = ByteOrder.LittleEndian;
                Debug.WriteLine("buffer lntgh: " + dataReader.UnconsumedBufferLength);
                while (dataReader.UnconsumedBufferLength != 0)
                {
                    Code   code = (Code)dataReader.ReadInt32();
                    Packet p;
                    switch (code)
                    {
                    case Code.Connecting:
                    {
                        Connected = true;
                        hostName  = args.RemoteAddress;
                        Debug.WriteLine("Connected to: " + hostName);
                        try
                        {
                            Stream output = (await socket.GetOutputStreamAsync(hostName, Port)).AsStreamForWrite();
                            writer = new BinaryWriter(output);
                        }
                        catch (Exception e)
                        {
                            Debug.WriteLine(e.Message);
                        }
                        send_buffer.Add(new Connected());
                        p = null;
                        break;
                    }

                    case Code.Ping:
                    {
                        p = Ping.ConstructPacket(dataReader);
                        break;
                    }

                    case Code.Pong:
                    {
                        p = Pong.ConstructPacket(dataReader);
                        break;
                    }

                    case Code.Acknowledge:
                    {
                        p = Acknowledge.ConstructPacket(dataReader);
                        break;
                    }

                    case Code.OtherPlayerCreationData:
                    {
                        p = AddOtherPlayer.ConstructPacket(dataReader);
                        send_buffer.Add(new Acknowledge(p.Code));
                        break;
                    }

                    case Code.Input:
                    {
                        p = Input.ConstructPacket(dataReader);
                        break;
                    }

                    case Code.EntityXYCorrection:
                    {
                        p = EntityCorrection.ConstructPacket(dataReader);
                        break;
                    }

                    default: p = null; break;
                    }

                    if (p != null)
                    {
                        receive_buffer.Add(p);
                    }
                    else
                    {
                        Debug.WriteLine("Unrecognized packet " + code);
                        break;
                    }
                }
            }
        }
コード例 #27
0
        private async void server_MessageReceived(DatagramSocket sender, DatagramSocketMessageReceivedEventArgs args)
        {
            // Get InputStream
            BinaryReader reader;

            try
            {
                reader = new BinaryReader(args.GetDataStream().AsStreamForRead());
            }
            catch (Exception e)
            {
                if (SocketError.GetStatus(e.HResult) != SocketErrorStatus.ConnectionResetByPeer)
                {
                    throw;
                }
                return;
            }

            byte[] header                = reader.ReadBytes(8);
            string headerstr             = Encoding.UTF8.GetString(header, 0, header.Length);
            Guid   guid                  = new Guid(reader.ReadBytes(16));
            ServerMessageHandler handler = ServerMessageHandler.Close;

            // Identify the handler
            if (clientList.ContainsKey(guid) && clientList[guid].Closing)
            {
                handler = ServerMessageHandler.Close;
            }
            else if (!clientList.ContainsKey(guid) && headerstr != "SHClCONN" && headerstr != "SHClPING")
            {
                handler = ServerMessageHandler.Close;
            }
            else
            {
                if (headerstr == "SHClPING")
                {
                    handler = ServerMessageHandler.Ping;
                }
                if (headerstr == "SHClCONN")
                {
                    handler = ServerMessageHandler.Connect;
                }
                if (headerstr == "SHClCLSE")
                {
                    handler = ServerMessageHandler.Close;
                }
                if (headerstr == "SHClDATA")
                {
                    handler = ServerMessageHandler.Data;
                }
                if (headerstr == "SHClSLNT")
                {
                    handler = ServerMessageHandler.Silent;
                }
            }

            BinaryWriter writer = null;

            // For data, we don't need to get the output stream
            if (handler != ServerMessageHandler.Data && handler != ServerMessageHandler.Silent)
            {
                var outputStream = await sender.GetOutputStreamAsync(args.RemoteAddress, args.RemotePort);

                writer = new BinaryWriter(outputStream.AsStreamForWrite());
            }

            // Handle the message
            switch (handler)
            {
            case ServerMessageHandler.Close:
                Header_CLSE(guid, writer);
                break;

            case ServerMessageHandler.Connect:
                Header_CONN(guid, reader, writer);
                break;

            case ServerMessageHandler.Ping:
                Header_PING(guid, writer);
                break;

            case ServerMessageHandler.Data:
                Header_DATA(guid, reader);
                break;

            case ServerMessageHandler.Silent:
                Header_SLNT(guid);
                break;
            }
        }
コード例 #28
0
        /// <summary>
        /// Sends DHCP reply
        /// </summary>
        /// <param name="msgType">Type of DHCP message to send</param>
        /// <param name="ip">IP for client</param>
        /// <param name="replyData">Reply options (will be sent if requested)</param>
        /// <param name="otherForceOptions">Force reply options (will be sent anyway)</param>
        private async void SendDHCPReply(DHCPMsgType msgType, IPAddress ip, DHCPReplyOptions replyData, Dictionary <DHCPOption, byte[]> otherForceOptions, IEnumerable <DHCPOption> forceOptions)
        {
            var replyBuffer = requestData;

            replyBuffer.op     = 2;                    // Reply
            replyBuffer.yiaddr = ip.GetAddressBytes(); // Client's IP
            if (replyData.ServerIpAddress != null)
            {
                replyBuffer.siaddr = replyData.ServerIpAddress.GetAddressBytes();
            }
            replyBuffer.options = CreateOptionStruct(msgType, replyData, otherForceOptions, forceOptions); // Options
            if (!string.IsNullOrEmpty(dhcpServer.ServerName))
            {
                var serverNameBytes = Encoding.ASCII.GetBytes(dhcpServer.ServerName);
                int len             = (serverNameBytes.Length > 63) ? 63 : serverNameBytes.Length;
                Array.Copy(serverNameBytes, replyBuffer.sname, len);
                replyBuffer.sname[len] = 0;
            }
            //lock (requestSocket)
            {
                var DataToSend = BuildDataStructure(replyBuffer);
                if (DataToSend.Length < 300)
                {
                    var sendArray = new byte[300];
                    Array.Copy(DataToSend, 0, sendArray, 0, DataToSend.Length);
                    DataToSend = sendArray;
                }

                if ((replyBuffer.giaddr[0] == 0) && (replyBuffer.giaddr[1] == 0) &&
                    (replyBuffer.giaddr[2] == 0) && (replyBuffer.giaddr[3] == 0))
                {
                    //requestSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, true);
                    //endPoint = new IPEndPoint(dhcpServer.BroadcastAddress, PORT_TO_SEND_TO_CLIENT);

                    //var udp = new UdpClient();
                    //udp.EnableBroadcast = true;
                    //udp.Send(DataToSend, DataToSend.Length, new IPEndPoint(dhcpServer.BroadcastAddress, 68));
                    //udp.Close();

                    var datagramsocket = new Windows.Networking.Sockets.DatagramSocket();

                    using (var stream = await datagramsocket.GetOutputStreamAsync(new Windows.Networking.HostName(dhcpServer.BroadcastAddress), PORT_TO_SEND_TO_CLIENT.ToString()))
                    {
                        using (var datawriter = new Windows.Storage.Streams.DataWriter(stream))
                        {
                            datawriter.WriteBytes(DataToSend);
                            await datawriter.StoreAsync();
                        }
                    }
                }
                else
                {
                    //requestSocket .SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, false);
                    //endPoint = new IPEndPoint(new IPAddress(replyBuffer.giaddr), PORT_TO_SEND_TO_RELAY);
                    //requestSocket.SendTo(DataToSend, endPoint);

                    using (var stream = await requestSocket.GetOutputStreamAsync(new Windows.Networking.HostName(new IPAddress(replyBuffer.giaddr).ToString()), PORT_TO_SEND_TO_RELAY.ToString()))
                    {
                        using (var datawriter = new Windows.Storage.Streams.DataWriter(stream))
                        {
                            datawriter.WriteBytes(DataToSend);
                            await datawriter.StoreAsync();
                        }
                    }
                }
            }
        }
コード例 #29
0
        private static async void MessageReceived(DatagramSocket sender, DatagramSocketMessageReceivedEventArgs args)
        {
            try
            {
                if (App.isRPi && peer == null)
                {
                    IOutputStream outputStream = await sender.GetOutputStreamAsync(args.RemoteAddress, args.RemotePort);

                    // It might happen that the OnMessage was invoked more than once before the GetOutputStreamAsync call
                    // completed. In this case we will end up with multiple streams - just keep one of them.
                    object syncRoot = new object();
                    lock (syncRoot)
                    {
                        peer = new RemotePeer(outputStream, args.RemoteAddress, args.RemotePort);
                    }

                    socketIsConnected = true;
                }

                var readPacket = args.GetDataReader();

                if (readPacket == null)
                {
                    Debug.WriteLine("DataReader is null");
                    return;
                }

                uint buffLen = readPacket.UnconsumedBufferLength;

                if (buffLen == 0)
                {
                    Debug.WriteLine("Buffer is empty");
                    return;
                }

                List <byte> bytes = new List <byte>();
                while (buffLen > 0)
                {
                    byte b = readPacket.ReadByte();
                    bytes.Add(b);
                    buffLen--;
                }

                lastCmdReceived = MainPage.stopwatch.ElapsedMilliseconds;

                if (App.isRPi)
                {
                    if (bytes[0] == '#')
                    {
                        MultiWii.evaluateCustomCommand(bytes);
                    }
                    else
                    {
                        MultiWii.sendRequestMSP(bytes);
                    }
                }
                else
                {
                    if (bytes[0] == '#')
                    {
                        MultiWii.evaluateCustomCommand(bytes);
                    }
                    else
                    {
                        MultiWii.evaluateResponseMSP(bytes);
                    }

                    await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
                    {
                        var currentPage     = ((ContentControl)Window.Current.Content).Content as Page;
                        var droneStatus     = currentPage.FindName("droneStatus") as Image;
                        droneStatus.Opacity = 1;
                    });
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine("OnConnection() - " + ex.Message);
            }
        }
コード例 #30
0
        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());
        }