Esempio n. 1
0
        public UDPWrapper(string receivesFrom, int receivesOn, string sendsTo, int sendsOn)
        {
            this.receivesFrom = receivesFrom;
            this.receivesOn   = receivesOn;

            this.sendsTo = sendsTo;
            this.sendsOn = sendsOn;

            Console.WriteLine("Binding to " + this.localIp + " on " + this.receivesOn);

            client.ConnectAsync(receivesFrom, receivesOn);

            //_socket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.ReuseAddress, true);
            //_socket.Bind(new IPEndPoint(IPAddress.Any, 0));

            IPHostEntry ipHostInfo    = Dns.GetHostEntry(Dns.GetHostName());
            IPAddress   ipAddress     = ipHostInfo.AddressList[0];
            IPEndPoint  localEndPoint = new IPEndPoint(ipAddress, receivesOn);

            // Create a TCP/IP socket.
            _socket = new Socket(ipAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
            _socket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.ReuseAddress, true);
            _socket.ReceiveTimeout = int.MaxValue;
            _socket.SendTimeout    = int.MaxValue;

            _socket.Bind(new IPEndPoint(IPAddress.Any, 0));
            //_socket.Bind(localEndPoint);
            _socket.Listen(100);

            allDone.Reset();
        }
Esempio n. 2
0
        private void InitView()
        {
            Content = new StackLayout()
            {
                Padding  = new Thickness(0, Device.OnPlatform(20, 0, 0), 0, 0),
                Children =
                {
                    new ClientConnectView("127.0.0.1",                                                          11011, this)
                    {
                        ConnectTapped = async(s,                                    i) =>
                        {
                            await _client.ConnectAsync(s,                           i);
                            _canceller = new CancellationTokenSource();

                            _client.MessageReceived += (sender,                     args) =>
                            {
                                var data = args.ByteData.ToStringFromUTF8Bytes();
                                var from = String.Format("{0}:{1}",                 args.RemoteAddress, args.RemotePort);

                                var msg = new Message
                                {
                                    Text       = data,
                                    DetailText =
                                        String.Format("<Received from {1} at {0}>", DateTime.Now.ToString("HH:mm:ss"),
                                                      from)
                                };

                                _messagesSub.OnNext(msg);
                            };

                            return(true);
                        },
                        DisconnectTapped = async() =>
                        {
                            var bytes = "<EOF>".ToUTF8Bytes();
                            await _client.SendAsync(bytes);

                            _canceller.Cancel();
                            await _client.DisconnectAsync();
                        }
                    },
                    new MessagesView(_messagesObs,                                  true)
                    {
                        SendData = async s =>
                        {
                            var bytes = s.ToUTF8Bytes();
                            await _client.SendAsync(bytes);

                            return(new Message
                            {
                                Text = s,
                                DetailText = String.Format("Sent at {0}",           DateTime.Now.ToString("HH:mm:ss"))
                            });
                        }
                    }
                }
            };
        }
Esempio n. 3
0
        /// <summary>
        /// Connect to a client
        /// </summary>
        public async Task <bool> ConnectAsync(string ip, int port)
        {
            try
            {
                // if you need a duplex TCP sample, take a look at SmartHome sample
                socketClient = new UdpSocketClient();
                socketClient.MessageReceived += SocketClient_MessageReceived;
                Serializer = new ProtobufNetworkSerializer();
                await socketClient.ConnectAsync(ip, port);

                StartSendingKeepAlive();
                Connected = true;
            }
            catch (Exception)
            {
                return(false);
            }
            return(true);
        }
        private static async Task <List <string> > BroadcastUDP(string ipAddress)
        {
            const int UDP_TIMEOUT_MS = 4000;

            using (var client = new UdpSocketClient())
            {
                var msg     = Encoding.UTF8.GetBytes("SoundBox");
                var replies = new List <string>();
                var port    = int.Parse(SoundBoxServer.TCP_SERVER_PORT);

                AutoResetEvent repliedEvent = new AutoResetEvent(false);

                client.MessageReceived += new EventHandler <UdpSocketMessageReceivedEventArgs>(
                    delegate(object sender, UdpSocketMessageReceivedEventArgs args)
                {
                    var reply = Encoding.UTF8.GetString(args.ByteData, 0, args.ByteData.Length);
                    var tab   = Convert.ToChar(9);
                    if (reply.Contains("SoundBox" + tab))
                    {
                        var parts = reply.Split(tab);
                        if (!replies.Contains(parts[1]))
                        {
                            replies.Add(parts[1]);
                        }
                    }

                    repliedEvent.Set();
                });

                // unusual! overcomes problem in limitation?
                await client.SendToAsync(msg, ipAddress, port);

                await client.ConnectAsync(ipAddress, port);

                await client.SendAsync(msg);

                repliedEvent.WaitOne(TimeSpan.FromMilliseconds(UDP_TIMEOUT_MS));

                return(replies);
            }
        }
Esempio n. 5
0
        async public static Task <ServerList> BrowseForNoahServers(string friendlyName, string ipAddress)
        {
            var client   = new UdpSocketClient();
            var receiver = new UdpSocketReceiver();

            try
            {
                var address = GetIpAddressForBroadcast(ipAddress);
                //// convert our greeting message into a byte array
                string clientGUID        = "{B0BE0E7D-F70B-40BE-91AB-14125863B0B7}";
                System.Text.Encoding enc = System.Text.Encoding.UTF8;
                byte[] sendBuffer        = enc.GetBytes(clientGUID);

                receiver.MessageReceived += (sender, args) =>
                {
                    try
                    {
                        var from   = String.Format("{0}:{1}", args.RemoteAddress, args.RemotePort);
                        var fromIp = args.RemoteAddress;
                        var data   = Encoding.UTF8.GetString(args.ByteData, 0, args.ByteData.Length);

                        try
                        {
                            LocalRemoteHostInfo payload =
                                Helpers.Deserialize <LocalRemoteHostInfo>(Encoding.UTF8.GetString(args.ByteData, 0,
                                                                                                  args.ByteData.Length));
                            string guid = payload.LocalNoahServerGuid;
                            if (guid.Equals("{5FE140D5-1D3F-4E46-8892-15FA89DAE9F4}"))
                            {
                                bool duplicate = false;
                                foreach (ServerData servData in ServerCollection)
                                {
                                    if (servData.ServerIp.Equals(fromIp))
                                    {
                                        duplicate = true; //The adress is allready in the list
                                        break;
                                    }
                                }
                                if (duplicate == false) //No need to list Gatteway IP
                                {
                                    if (string.IsNullOrEmpty(friendlyName))
                                    {
                                        ServerCollection.Add(new ServerData
                                        {
                                            ServerName   = payload.HostName,
                                            FriendlyName = payload.FriendlyName,
                                            ServerIp     = payload.LocalHostIpAddress,
                                            RemoteHostId = payload.RemoteHostId
                                        });
                                    }
                                    else
                                    {
                                        if (friendlyName == payload.FriendlyName)
                                        {
                                            receiver.StopListeningAsync();
                                            ServerCollection.Add(new ServerData
                                            {
                                                ServerName   = payload.HostName,
                                                FriendlyName = payload.FriendlyName,
                                                ServerIp     = payload.LocalHostIpAddress,
                                                RemoteHostId = payload.RemoteHostId
                                            });

                                            //client.Dispose();
                                            //receiver.Dispose();
                                            waitTime = false;
                                        }
                                    }
                                }
                            }
                        }
                        catch { }
                    }
                    catch { }
                };
                try
                {
                    receiver.StartListeningAsync(listenPort);
                }
                catch (Exception e)
                {
                }
                client.ConnectAsync(address, port);
                client.SendAsync(sendBuffer);

                DateTime now  = DateTime.Now;
                DateTime stop = now + new TimeSpan(0, 0, 0, 5);


                while (waitTime)
                {
                    if (DateTime.Now > stop)
                    {
                        waitTime = false;
                    }
                }
            }
            catch (Exception e)
            {
                Log.ErrorFormat("Himsa.Noah.MobileAccessLayer.NoahServerUdpBrowser::BrowseForNoahServers(): {0}", e);
                throw;
            }
            finally
            {
                client.DisconnectAsync();
                receiver.StopListeningAsync();
                receiver.Dispose();
            }

            return(new ServerList
            {
                Servers = ServerCollection.ToArray()
            });
        }