GetOutputStreamAsync() private method

private GetOutputStreamAsync ( [ endpointPair ) : IAsyncOperation
endpointPair [
return IAsyncOperation
Esempio n. 1
0
		public static async void init(TiSettings settings) {
			if (!settings.ContainsKey("logToken") || settings["logToken"].Length == 0) {
				return;
			}

			logToken = settings["logToken"];

			multicastSocket = new DatagramSocket();
			multicastSocket.MessageReceived += multicastSocket_MessageReceived;

			HostName hostname = new HostName("239.6.6.6");

			try {
				await multicastSocket.BindServiceNameAsync("8666");
				multicastSocket.JoinMulticastGroup(hostname);

				IOutputStream stream = await multicastSocket.GetOutputStreamAsync(hostname, "8666");
				DataWriter writer = new DataWriter(stream);
				writer.WriteString("TI_WP8_LOGGER");
				await writer.StoreAsync();
				writer.DetachStream();
				stream.Dispose();
			} catch (Exception ex) {
				if (SocketError.GetStatus(ex.HResult) == SocketErrorStatus.Unknown) {
					throw;
				}
				Debug.WriteLine(ex.ToString());
			}
		}
Esempio n. 2
0
        private async void btnConnect_Click(object sender, RoutedEventArgs e)
        {
            Windows.Networking.Sockets.DatagramSocket socket = new Windows.Networking.Sockets.DatagramSocket();

            socket.MessageReceived += Socket_MessageReceived;

            //You can use any port that is not currently in use already on the machine. We will be using two separate and random
            //ports for the client and server because both the will be running on the same machine.
            string serverPort = "8001";
            string clientPort = "8002";

            //Because we will be running the client and server on the same machine, we will use localhost as the hostname.
            Windows.Networking.HostName serverHost = new Windows.Networking.HostName("127.0.0.1");

            //Bind the socket to the clientPort so that we can start listening for UDP messages from the UDP echo server.
            await socket.BindServiceNameAsync(clientPort);

            await socket.ConnectAsync(serverHost, serverPort);

            //Write a message to the UDP echo server.
            Stream       streamOut = (await socket.GetOutputStreamAsync(serverHost, serverPort)).AsStreamForWrite();
            StreamWriter writer    = new StreamWriter(streamOut);
            string       message   = "I'm the message from client!";
            await writer.WriteLineAsync(message);

            await writer.FlushAsync();
        }
Esempio n. 3
0
        private async void SendMessage_Click(object sender, RoutedEventArgs e)
        {
            SendOutput.Text = "";

            try
            {
                var remoteHostname = new HostName(RemoteAddress.Text);
                var outputStream   = await listenerSocket.GetOutputStreamAsync(remoteHostname, ServiceName.Text);

                const string stringToSend = "Hello";
                var          writer       = new DataWriter(outputStream);
                writer.WriteString(stringToSend);
                await writer.StoreAsync();

                SendOutput.Text = "\"" + stringToSend + "\" sent successfully.";
            }
            catch (Exception exception)
            {
                if (SocketError.GetStatus(exception.HResult) == SocketErrorStatus.Unknown)
                {
                    throw;
                }

                _rootPage.NotifyUser("Send failed with error: " + exception.Message, NotifyType.ErrorMessage);
            }
        }
Esempio n. 4
0
    public async void DoesAThing()
    {
      var hostName = new HostName("stun.l.google.com");
      var port = 19302;
      var taskCompletionSource = new TaskCompletionSource<StunUri>();
      using (var datagramSocket = new DatagramSocket())
      {
        datagramSocket.MessageReceived += async (sender, e) =>
        {
          var buffer = await e.GetDataStream().ReadAsync(null, 100, InputStreamOptions.None).AsTask();
          var stunMessage = StunMessage.Parse(buffer.ToArray());
          var xorMappedAddressStunMessageAttribute = stunMessage.Attributes.OfType<XorMappedAddressStunMessageAttribute>().Single();
          taskCompletionSource.SetResult(new StunUri(xorMappedAddressStunMessageAttribute.HostName, xorMappedAddressStunMessageAttribute.Port));
        };

        using (var inMemoryRandomAccessStream = new InMemoryRandomAccessStream())
        {
          var stunMessageId = new StunMessageId(CryptographicBuffer.GenerateRandom(12).ToArray());
          var stunMessageType = StunMessageType.BindingRequest;
          var stunMessageAttributes = new StunMessageAttribute[] { };
          var stunMessage = new StunMessage(stunMessageType, stunMessageAttributes, stunMessageId);
          var bytes = stunMessage.ToLittleEndianByteArray();
          var outputStream = await datagramSocket.GetOutputStreamAsync(hostName, $"{port}");
          var written = await outputStream.WriteAsync(bytes.AsBuffer());
        }
      }

      var result = await taskCompletionSource.Task;
      Assert.AreEqual(result.HostName, new HostName("200.100.50.25"));
      Assert.AreEqual(result.Port, 12345);
    }
Esempio n. 5
0
        public async void SendMsg(string msg)
        {
            Stream       streamOut = (await socket.GetOutputStreamAsync(serverHost, serverPort)).AsStreamForWrite();
            StreamWriter writer    = new StreamWriter(streamOut);
            await writer.WriteLineAsync(msg);

            await writer.FlushAsync();
        }
		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");
				}
			}
		}
        /// <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;
            }
        }       
Esempio n. 8
0
    /// <summary>
    /// Returns list of bridge IPs
    /// </summary>
    /// <returns></returns>
    public async Task<IEnumerable<string>> LocateBridgesAsync(TimeSpan timeout)
    {
      if (timeout <= TimeSpan.Zero)
        throw new ArgumentException("Timeout value must be greater than zero.", "timeout");

      var discoveredDevices = new List<string>();
      var multicastIP = new HostName("239.255.255.250");
      
      using (var socket = new DatagramSocket())
      {

        //Handle MessageReceived
        socket.MessageReceived += (sender, e) =>
        {
          var reader = e.GetDataReader();
          var bytesRemaining = reader.UnconsumedBufferLength;
          var receivedString = reader.ReadString(bytesRemaining);

          var location = receivedString.Substring(receivedString.ToLower().IndexOf("location:", System.StringComparison.Ordinal) + 9);
          receivedString = location.Substring(0, location.IndexOf("\r", System.StringComparison.Ordinal)).Trim();

          discoveredDevices.Add(receivedString);
        };

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

        var start = DateTime.Now;

        do
        {
          using (var stream = await socket.GetOutputStreamAsync(multicastIP, "1900"))
          using (var writer = new DataWriter(stream))
          {
            string request = "M-SEARCH * HTTP/1.1\r\n" +
                         "HOST:239.255.255.250:1900\r\n" +
                         //"ST:urn:schemas-upnp-org:device:Basic:1\r\n" + //Alternative
                         // "ST:upnp:rootdevice\r\n" +                    //Alternative
                         "ST:SsdpSearch:all\r\n" +
                         "MAN:\"ssdp:discover\"\r\n" +
                         "MX:3\r\n\r\n\r\n";

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

          }

        }
        while (DateTime.Now.Subtract(start) < timeout); // try for thee seconds
      }

      return await FilterBridges(discoveredDevices);

    }
Esempio n. 9
0
        private async void OnMessageReceived(
            DatagramSocket sender,
            DatagramSocketMessageReceivedEventArgs args)
        {
            var senderHostname = new HostName(args.RemoteAddress.RawName);

            var writer = new DataWriter(await sender.GetOutputStreamAsync(senderHostname, args.RemotePort));

            var stream = new NetworkStream(args.GetDataReader(), writer);

            this.clients.ForEach(x => x.MessageReceived(this, stream));
        }
        private async Task DoWakeOnLan(string macAddress, string ipAddress, string port)
        {
            var socket = new DatagramSocket();

            await socket.BindServiceNameAsync("0");

            var o = await socket.GetOutputStreamAsync(new HostName(ipAddress), port);
            var writer = new DataWriter(o);
            writer.WriteBytes(GetBuffer(macAddress));
            await writer.StoreAsync();

            socket.Dispose();
        }
Esempio n. 11
0
        public async void StartServer(string port)
        {
            _socket = new DatagramSocket();

            var control = _socket.Control;
            _socket.MessageReceived += OnMessageRecived;
            await _socket.BindServiceNameAsync(port);

            var host = new HostName("192.168.137.1");
            var outputStream = await _socket.GetOutputStreamAsync(host, "8001");
            _writer = new DataWriter(outputStream);

        }
Esempio n. 12
0
        private async void Search(string st, TimeSpan? timeout = null)
        {
            Log("Search - " + st);

            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 adapters = TargetNetworkAdapters ?? await GetActiveAdaptersAsync().ConfigureAwait(false);

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

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

                        using (var output = await socket.GetOutputStreamAsync(MULTICAST_HOST, SSDP_PORT.ToString()))
                        {
                            using (var writer = new DataWriter(output))
                            {
                                writer.WriteString(ssdp_data);
                                await writer.StoreAsync();
                            }
                        }

                        await Task.Delay(timeout ?? DEFAULT_TIMEOUT).ConfigureAwait(false);
                        Log("Search Timeout");
                        await socket.CancelIOAsync();
                    }
                    catch (Exception e)
                    {
                        Log("Failed to send multicast: " + e.StackTrace);
                    }

                    socket.MessageReceived -= OnDatagramSocketMessageReceived;
                }
            })).ConfigureAwait(false);

            Finished?.Invoke(this, new EventArgs());
        }
 private async Task SendTick()
 {
     using (var socket = new DatagramSocket())
     {
         await socket.BindServiceNameAsync(string.Empty);
         socket.JoinMulticastGroup(new HostName(BroadcastAddress));
         var outputStream =
             await socket.GetOutputStreamAsync(new HostName(BroadcastAddress), RemoteServiceName);
         var buffer = Encoding.UTF8.GetBytes("TT_SEND_DEVICE_INFO");
         await outputStream.WriteAsync(buffer.AsBuffer());
         await outputStream.FlushAsync();
         Debug.WriteLine("TICK Broadcasted to {0}:{1}", BroadcastAddress, RemoteServiceName);
     }
 }
        private async void _socket_OnMessageReceived(DatagramSocket sender, DatagramSocketMessageReceivedEventArgs e)
        {
            var reader = e.GetDataReader();
            string message = reader.ReadString(reader.UnconsumedBufferLength);

            Logger.Trace("Message from {0}:{1}:\n{2}", e.RemoteAddress.RawName, e.RemotePort, message);

            IOutputStream outputStream = await sender.GetOutputStreamAsync(e.RemoteAddress, e.RemotePort);
            Received(this, new PeerCommandEventArgs
                               {
                                   Data = message,
                                   Peer = new RemotePeer(_serializer, this, outputStream, e.RemoteAddress, e.RemotePort),
                               });
        }
Esempio n. 15
0
        public async Task<List<ServerDiscoveryInfo>> FindServers(int timeoutMs, CancellationToken cancellationToken)
        {
            var result = new List<ServerDiscoveryInfo>();

            var tcs = new TaskCompletionSource<List<ServerDiscoveryInfo>>();

            var ct = new CancellationTokenSource(timeoutMs);
            ct.Token.Register(() => tcs.SetResult(result), useSynchronizationContext: false);

            var socket = new DatagramSocket();
            socket.MessageReceived += (sender, args) =>
            {
                try
                {
                    var reader = args.GetDataReader();

                    uint stringLength = args.GetDataReader().UnconsumedBufferLength;
                    var rawData = args.GetDataReader().ReadString(stringLength);

                    var server = JsonConvert.DeserializeObject<ServerDiscoveryInfo>(rawData);

                    result.Add(server);
                }
                catch
                {
                    tcs.SetResult(result);
                }
            };

            try
            {
                using (var stream = await socket.GetOutputStreamAsync(new HostName("255.255.255.255"), "7359"))
                {
                    using (var writer = new DataWriter(stream))
                    {
                        var data = Encoding.UTF8.GetBytes("who is MediaBrowserServer_v2?");

                        writer.WriteBytes(data);
                        writer.StoreAsync();
                    }
                }
            }
            catch
            {
                tcs.SetResult(result);
            }

            return await tcs.Task;
        }
Esempio n. 16
0
 public async Task Send(byte[] command)
 {
     using (var socket = new DatagramSocket())
     {
         using (var stream = await socket.GetOutputStreamAsync(this.hostName, this.port))
         {
             using (var dataWriter = new DataWriter(stream))
             {
                 dataWriter.WriteBytes(command);
                 await dataWriter.StoreAsync();
                 dataWriter.DetachStream();
             }
         }
     }
 }
Esempio n. 17
0
        public async Task DiscoverDevices()
        {
            string response = String.Empty;

            DatagramSocket socket = new DatagramSocket();
            socket.MessageReceived += Socket_MessageReceived;

            using (var stream = await socket.GetOutputStreamAsync(new HostName("255.255.255.255"), OSCClient.PORT))
            using (var writer = new DataWriter(stream))
            {
                OSCMessage msg = new OSCMessage("/info");
                writer.WriteBytes(msg.BinaryData);
                await writer.StoreAsync();
            }
        }
        public async void Search()
        {
            if (isSearching)
                return;

            isSearching = true;

            var socket = new DatagramSocket();
            socket.MessageReceived += async (sender, args) =>
            {
                DataReader reader = args.GetDataReader();

                uint count = reader.UnconsumedBufferLength;
                string data = reader.ReadString(count);
                var response = new Dictionary<string, string>();
                foreach (
                    string x in
                        data.Split(new[] { "\r\n", "\n" }, StringSplitOptions.None))
                {
                    if (x.Contains(":"))
                    {
                        string[] strings = x.Split(':');
                        response.Add(strings[0].ToLower(), x.Remove(0, strings[0].Length + 1));
                    }
                }

                Device device = await GetXml(response);
                Debug.WriteLine($"Device found : {device.DeviceType.friendlyName}");

                if (DeviceFound != null)
                    DeviceFound(this, new DeviceFoundEventArgs(device));
            };

            IOutputStream stream = await socket.GetOutputStreamAsync(new HostName("239.255.255.250"), "1900");


            const string message = "M-SEARCH * HTTP/1.1\r\n" +
                                   "HOST: 239.255.255.250:1900\r\n" +
                                   "ST:upnp:rootdevice\r\n" +
                                   "MAN:\"ssdp:discover\"\r\n" +
                                   "MX:3\r\n\r\n";

            var writer = new DataWriter(stream) { UnicodeEncoding = Windows.Storage.Streams.UnicodeEncoding.Utf8 };
            writer.WriteString(message);
            await writer.StoreAsync();

            isSearching = false;
        }
Esempio n. 19
0
 public async Task SendMessage(byte[] message, string host, string port)
 {
     sender = new DatagramSocket();
     try
     {
         using (var stream = await sender.GetOutputStreamAsync(new HostName(host), port))
         {
             var writer = new DataWriter(stream);
             writer.WriteBytes(message);
             await writer.StoreAsync();
             playPage.DisplayMessages(name + " :Send message");
         }
     }
     catch (Exception ex)
     {
         playPage.DisplayMessages(name + " :Error: Send Message\n" + ex.ToString());
     }
     sender.Dispose();
 }
Esempio n. 20
0
        /// <summary>
        /// @see http://www.johnthom.com/implementing-ssdp-search-in-windows-phone-8-using-winrt/
        /// </summary>
        public async Task DiscoverDevices()
        {
            int timeout = 3000;
            var remoteIp = "239.255.255.250";
            var remoteIpHostName = new Windows.Networking.HostName(remoteIp);
            var port = "1900";

            string query = "M-SEARCH * HTTP/1.1\r\n" +
                         "HOST: 239.255.255.250:1900\r\n" +
                         "ST: upnp:rootdevice\r\n" +
                         "MAN: \"ssdp:discover\"\r\n" +
                         "MX: " + timeout.ToString() + "\r\n\r\n";

            var buffer = Encoding.UTF8.GetBytes(query);

            using (var socket = new DatagramSocket())
            {
                socket.MessageReceived += (sender, args) => {
                    Task.Run(() => {
                        using (var reader = args.GetDataReader())
                        {
                            byte[] respBuff = new byte[reader.UnconsumedBufferLength];
                            reader.ReadBytes(respBuff);
                            string response = Encoding.UTF8.GetString(respBuff, 0, respBuff.Length).ToLower();
                            response.Trim('\0');

                            ProcessSSDPResponse(response);
                        }
                    });
                };

                await socket.BindEndpointAsync(null, "");
                socket.JoinMulticastGroup(remoteIpHostName);
                
                using (var stream = await socket.GetOutputStreamAsync(remoteIpHostName, port))
                {
                    await stream.WriteAsync(buffer.AsBuffer());
                }
                
                // Execute within timeout
                await Task.Delay(timeout);
            }
        }
        // Listenerがメッセージを受信したときのハンドラ
        private async void MessageReceivedAsync(Windows.Networking.Sockets.DatagramSocket socket, DatagramSocketMessageReceivedEventArgs args)
        {
            if (CoreApplication.Properties.TryGetValue("remotePeer", out var outObj))
            {
                EchoMessage((RemotePeer)outObj, args);
                return;
            }

            try
            {
                // SenderのアドレスとポートからOutputStreamを取得
                var outputStream = await socket.GetOutputStreamAsync(
                    args.RemoteAddress,
                    args.RemotePort);

                RemotePeer peer;
                lock (this)
                {
                    if (CoreApplication.Properties.TryGetValue("remotePeer", out outObj))
                    {
                        peer = (RemotePeer)outObj;
                    }
                    else
                    {
                        peer = new RemotePeer(outputStream, args.RemoteAddress, args.RemotePort);
                        CoreApplication.Properties.Add("remotePeer", peer);
                    }
                }

                EchoMessage(peer, args);
            }
            catch (Exception exception)
            {
                if (SocketError.GetStatus(exception.HResult) == SocketErrorStatus.Unknown)
                {
                    throw;
                }

                NotifyUserFromAsyncThread("Connect failed with error: " + exception.Message, NotifyType.ErrorMessage);
            }
        }
Esempio n. 22
0
 public static IObservable<ZeroconfRecord> Resolve(string protocol)
 {
     return Observable.Create<ZeroconfRecord>(async observer =>
         {
             var socket = new DatagramSocket();
             var s = Observable
                 .FromEventPattern
                 <TypedEventHandler<DatagramSocket, DatagramSocketMessageReceivedEventArgs>,
                     DatagramSocketMessageReceivedEventArgs>(
                         x => socket.MessageReceived += x, _ => socket.Dispose())
                 .Select(ProcessMessage)
                 .Where(x => x != null)
                 .Subscribe(observer);
             await socket.BindServiceNameAsync("5353");
             socket.JoinMulticastGroup(new HostName("224.0.0.251"));
             var os = await socket.GetOutputStreamAsync(new HostName("224.0.0.251"), "5353");
             var writer = new DataWriter(os);
             WriteQueryMessage(protocol, writer);
             writer.StoreAsync();
             return s;
         });
 }
Esempio n. 23
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();
            }
        }
Esempio n. 24
0
        public async void Locate()
        {
            DatagramSocket socket = new DatagramSocket();
            socket.Control.DontFragment = true;
            socket.MessageReceived += MessageReceived;

            using (var stream = await socket.GetOutputStreamAsync(new HostName("192.168.1.255"), "8888"))
                using (var writer = new DataWriter(stream))
                {
                    writer.WriteBytes(Encoding.UTF8.GetBytes("SNC"));
                    await writer.StoreAsync();
                }
        }
        /// <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();
                        }
                    }
                }
            }
        }
Esempio n. 26
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();
            });
        }
        private async Task SendMessage(string message, int port)
        {
            FoundServers = new ObservableCollection<Server>();
            var socket = new DatagramSocket();

            socket.MessageReceived += SocketOnMessageReceived;

            using (var stream = await socket.GetOutputStreamAsync(new HostName("255.255.255.255"), port.ToString(CultureInfo.InvariantCulture)))
            {
                using (var writer = new DataWriter(stream))
                {
                    var data = Encoding.UTF8.GetBytes(message);

                    writer.WriteBytes(data);
                    writer.StoreAsync();
                }
            }
        }
Esempio n. 28
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());
        }
Esempio n. 29
0
        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;
                        }
                    }
                }
            }

        }
Esempio n. 30
0
		/// <summary>
		///     Searches for an available devices of specified type.
		/// </summary>
		/// <param name="searchTarget">
		///     The type of the devices to search for.
		/// </param>
		/// <param name="timeForResponse">
		///     The time (in seconds) of a search.
		/// </param>
		/// <returns>
		///     An observable collection which contains search results.
		/// </returns>
		public IObservable<SearchResponseMessage> Search(string searchTarget, int timeForResponse)
		{
			return Observable.Create<SearchResponseMessage>(async observer =>
			{
				var searchSocket = new DatagramSocket();

				// Handling responses from found devices
				searchSocket.MessageReceived += async (sender, args) =>
				{
					var dataReader = args.GetDataReader();
					dataReader.InputStreamOptions = InputStreamOptions.Partial;

					if (dataReader.UnconsumedBufferLength == 0)
					{
						await dataReader.LoadAsync(1024);
					}

					var message = dataReader.ReadString(dataReader.UnconsumedBufferLength);

					try
					{
						var response = SearchResponseMessage.Create(message);

						observer.OnNext(response);
					}
					catch (ArgumentException ex)
					{
						logger.Instance().Warning(ex, "The received M-Search response has been ignored.", "Message".As(message));
					}
				};

				await searchSocket.BindServiceNameAsync("0");
				searchSocket.JoinMulticastGroup(this.multicastHost);

				var request = MSearchRequestFormattedString.F(searchTarget, timeForResponse);
				var buffer = Encoding.UTF8.GetBytes(request).AsBuffer();

				// Sending the search request to a multicast group
				var outputStream = await searchSocket.GetOutputStreamAsync(this.multicastHost, MulticastPort.ToString());
				await outputStream.WriteAsync(buffer);
				await outputStream.WriteAsync(buffer);

				// Stop listening for a devices when timeout for responses is expired
				Observable.Timer(TimeSpan.FromSeconds(timeForResponse)).Subscribe(s =>
				{
					observer.OnCompleted();
					searchSocket.Dispose();
				});

				logger.Instance().Debug("M-Search request has been sent. [multicastHost={0}, searchTarget={1}]".F(multicastHost.DisplayName, searchTarget));
				return searchSocket.Dispose;
			});
		}
Esempio n. 31
0
        private static async Task BindToSocketAndWriteQuery(DatagramSocket socket, byte[] bytes, CancellationToken cancellationToken)
        {
#if !WINDOWS_PHONE
            try
            {
               // Try to bind using port 5353 first
               await socket.BindServiceNameAsync("5353", NetworkInformation.GetInternetConnectionProfile().NetworkAdapter)
                           .AsTask(cancellationToken)
                           .ConfigureAwait(false);

            }
            catch (Exception)
            {
                // If it fails, use the default
                await socket.BindServiceNameAsync("", NetworkInformation.GetInternetConnectionProfile().NetworkAdapter)
                            .AsTask(cancellationToken)
                            .ConfigureAwait(false);

            }
#else
            await socket.BindServiceNameAsync("5353")
                        .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();
            }
        }
Esempio n. 32
0
		private async Task JitterCalculation()
		{
			datagramSocket = new DatagramSocket();

			datagramSocket.MessageReceived += delegate(DatagramSocket socket, DatagramSocketMessageReceivedEventArgs args)
			{
				System.Diagnostics.Debug.WriteLine("[ProfileNetworkFull]: Jitter Finish");
			};

			string port = server.JitterTestPort.ToString();
			await datagramSocket.BindServiceNameAsync(port);
			using (DataWriter writer = new DataWriter(await datagramSocket.GetOutputStreamAsync(hostName, port)))
			{
				for (int i = 0; i < 21; i++)
				{
					writer.WriteString("jitter");
					await writer.StoreAsync();
					await writer.FlushAsync();

					await Task.Delay(250);
				}
			}

			Close(ref datagramSocket);
		}
Esempio n. 33
0
        private async void send_Click(object sender, RoutedEventArgs e)
        {
            HostName hostName = new HostName("localhost");
            DatagramSocket datagramSocket = new DatagramSocket();
            IOutputStream outputStream = await datagramSocket.GetOutputStreamAsync(hostName, "22112");
            DataWriter writer = new DataWriter(outputStream);
            writer.WriteString("test"+i);
            try
            {
                await writer.StoreAsync();
                msgList.Children.Add(new TextBlock { Text = "客户端发送的消息:" + "test" + i });
            }
            catch (Exception err)
            {
                if (SocketError.GetStatus(err.HResult) == SocketErrorStatus.AddressAlreadyInUse)
                {

                }
            }
        }
Esempio n. 34
0
 private async void SendMsg(string ip,string msg)
 {
     DatagramSocket udp = new DatagramSocket();
     HostName host = new HostName(ip);
     var outStream = await udp.GetOutputStreamAsync(host, "8788");
     DataWriter writer = new DataWriter(outStream);
     // 往流里面写数据
     writer.WriteString(msg);
     await writer.StoreAsync();
     writer.DetachStream();
 }
        /// <summary>
        /// Message received handler
        /// </summary>
        /// <param name="socket">The socket object</param>
        /// <param name="eventArguments">The datagram event information</param>
        async void MessageReceived(DatagramSocket socket, DatagramSocketMessageReceivedEventArgs eventArguments)
        {
            object outObj;
            if (CoreApplication.Properties.TryGetValue("remotePeer", out outObj))
            {
                EchoMessage((RemotePeer)outObj, eventArguments);
                return;
            }

            // We do not have an output stream yet so create one.
            try
            {
                IOutputStream outputStream = await socket.GetOutputStreamAsync(
                    eventArguments.RemoteAddress, 
                    eventArguments.RemotePort);

                // It might happen that the OnMessage was invoked more than once before the GetOutputStreamAsync call
                // completed. In this case we will end up with multiple streams - just keep one of them.
                RemotePeer peer;
                lock (this)
                {
                    if (CoreApplication.Properties.TryGetValue("remotePeer", out outObj))
                    {
                        peer = (RemotePeer)outObj;
                    }
                    else
                    {
                        peer = new RemotePeer(outputStream, eventArguments.RemoteAddress, eventArguments.RemotePort);
                        CoreApplication.Properties.Add("remotePeer", peer);
                    }
                }

                EchoMessage(peer, eventArguments);
            }
            catch (Exception exception)
            {
                // If this is an unknown status it means that the error is fatal and retry will likely fail.
                if (SocketError.GetStatus(exception.HResult) == SocketErrorStatus.Unknown)
                {
                    throw;
                }

                NotifyUserFromAsyncThread("Connect failed with error: " + exception.Message, NotifyType.ErrorMessage);
            }
        }