示例#1
0
        public async Task <StreamSocket> Client(HostName RemoteHost)
        {
            // 获取本机IP
            var HostNames = NetworkInformation.GetHostNames();
            var LocalHost = HostNames.FirstOrDefault(h =>
            {
                bool isIpaddr = h.Type == Windows.Networking.HostNameType.Ipv4;
                // 如果不是IP地址表示的名称,则忽略
                if (isIpaddr == false)
                {
                    return(false);
                }
                IPInformation ipinfo = h.IPInformation;
                // 71表示无线,6表示以太网
                if (ipinfo.NetworkAdapter.IanaInterfaceType == 71 || ipinfo.NetworkAdapter.IanaInterfaceType == 6)
                {
                    return(true);
                }
                return(false);
            });

            //尝试连接远程主机的1117端口
            EndpointPair EndPoint = new EndpointPair(LocalHost, "", RemoteHost, "1117");
            StreamSocket client   = new StreamSocket();
            await client.ConnectAsync(EndPoint);

            return(client);
        }
示例#2
0
        public async Task <StreamSocket> Client(HostName RemoteHost)
        {
            //var HostNames = NetworkInformation.GetHostNames();
            //var LocalHost = HostNames.FirstOrDefault(h =>
            //{
            //    bool isIpaddr = h.Type == Windows.Networking.HostNameType.Ipv4;
            //    // 如果不是IP地址表示的名称,则忽略
            //    if (isIpaddr == false)
            //    {
            //        return false;
            //    }
            //    IPInformation ipinfo = h.IPInformation;
            //    // 71表示无线,6表示以太网
            //    if (ipinfo.NetworkAdapter.IanaInterfaceType == 71 || ipinfo.NetworkAdapter.IanaInterfaceType == 6)
            //    {
            //        return true;
            //    }
            //    return false;
            //});
            var          LocalHost = new HostName("127.0.0.1");
            EndpointPair EndPoint  = new EndpointPair(LocalHost, "", RemoteHost, "1117");
            StreamSocket client    = new StreamSocket();
            await client.ConnectAsync(EndPoint);

            return(client);
        }
        public LoraNetworkClient(HostName hostName, int port)
        {
            _endpointPair = new EndpointPair(
                null,
                string.Empty,
                hostName,
                port.ToString());

            _udp = new DatagramSocket();
            _udp.Control.DontFragment = true;
            _udp.MessageReceived     += UdpMessageReceived;
        }
        public static void SendFiles(string remoteIP, int port, string[] filepaths)
        {
            new Task(async() =>
            {
                int serverPort            = Config.Ports.ClientServerConnection;
                EndpointPair endpointPair = new EndpointPair(new HostName(IPManager.GetLocalIpAddress()), port.ToString(), new HostName(remoteIP), serverPort.ToString());
                StreamSocket socket       = new StreamSocket();

                await socket.ConnectAsync(endpointPair);
                Socket_Base_Hololens.SendFilesAsync(filepaths, socket);

                socket.Dispose();
            }).Start();
        }
示例#5
0
        public override bool StartPing(string host)
        {
            base.Init();

            EndpointPair endPoint = new EndpointPair(null, string.Empty, new HostName(host), "5055");

            this.sock = new DatagramSocket();
            this.sock.MessageReceived += OnMessageReceived;

            var result = this.sock.ConnectAsync(endPoint);

            result.Completed  = this.OnConnected;
            this.DebugString += " End StartPing";
            return(true);
        }
        public static void RequestFiles(string serverIP, int port, string receiveDirectory)
        {
            new Task(async() =>
            {
                // Generate the socket and connect to the server
                StreamSocket socket = new StreamSocket();

                int serverPort            = Config.Ports.ClientServerConnection;
                EndpointPair endpointPair = new EndpointPair(new HostName(IPManager.GetLocalIpAddress()), port.ToString(), new HostName(serverIP), serverPort.ToString());
                await socket.ConnectAsync(endpointPair);

                // After awaiting the connection, receive data appropriately
                ReceiveFilesAsync(socket, receiveDirectory);

                socket.Dispose();
            }).Start();
        }
示例#7
0
        private async void Button_Click_1(object sender, RoutedEventArgs e)
        {
            Windows.Networking.Sockets.StreamSocket streamSocket = new Windows.Networking.Sockets.StreamSocket();
            HostName      localHost  = new HostName("localhost");
            HostName      remoteHost = new HostName("www.andrea-allievi.com");
            EndpointPair  ep         = new EndpointPair(localHost, "", remoteHost, "80");
            MessageDialog dlg        = new Windows.UI.Popups.MessageDialog("");

            // Save the socket, so subsequent steps can use it.
            Windows.ApplicationModel.Core.CoreApplication.Properties.Add("clientSocket", streamSocket);

            try
            {
                await streamSocket.ConnectAsync(remoteHost, "80");
            }
            catch (Exception exc)
            {
                // If this is an unknown status it means that the error is fatal and retry will likely fail.
                if (SocketError.GetStatus(exc.HResult) == SocketErrorStatus.Unknown)
                {
                    throw;
                }

                dlg.Title   = "Socket Error!";
                dlg.Content = "Connect failed with error: " + exc.Message;
                dlg.ShowAsync();
                return;
            }

            DataWriter writer = new DataWriter(streamSocket.OutputStream);

            writer.WriteString("GET /index.html\r\n");
            await writer.StoreAsync();

            DataReader reader = new DataReader(streamSocket.InputStream);
            uint       len    = 2048;

            reader.InputStreamOptions = InputStreamOptions.Partial;
            uint numStrBytes = await reader.LoadAsync(len);

            string data = reader.ReadString(numStrBytes);

            dlg.Title   = "Received data";
            dlg.Content = data;
            await dlg.ShowAsync();
        }
示例#8
0
        public override bool StartPing(string host)
        {
            lock (this.syncer)
            {
                this.Init();

                int          port     = (RegionHandler.PortToPingOverride != 0) ? RegionHandler.PortToPingOverride : 5055;
                EndpointPair endPoint = new EndpointPair(null, string.Empty, new HostName(host), port.ToString());
                this.sock = new DatagramSocket();
                this.sock.MessageReceived += this.OnMessageReceived;

                IAsyncAction result = this.sock.ConnectAsync(endPoint);
                result.Completed  = this.OnConnected;
                this.DebugString += " End StartPing";
                return(true);
            }
        }
示例#9
0
        protected async Task SendMessage(EndpointInformation message)
        {
            EndpointPair endpoint = new EndpointPair(
                new HostName(information.LocalAddress),
                information.MulticastPort,
                new HostName(information.MulticastAddress),
                information.MulticastPort
                );

            using (IOutputStream outputStream = await socket.GetOutputStreamAsync(endpoint))
                using (DataWriter writer = new DataWriter(outputStream))
                {
                    byte[] data = message.Serialize();
                    writer.WriteBytes(data);
                    await writer.StoreAsync();
                }
        }
示例#10
0
        /// <summary>
        /// Add underlying protocol endpoint and return created current protocol endpoint
        /// </summary>
        /// <param name="underProtoclEndpoint">The underlying protocol endpoint</param>
        /// <returns>The new created current protocol endpoint</returns>
        public T2 AddEndpoint(T1 underProtoclEndpoint)
        {
            EndpointPair <T1, T2> endpointPair = new EndpointPair <T1, T2>();

            endpointPair.UnderProtocolEndpoint   = underProtoclEndpoint;
            endpointPair.CurrentProtocolEndpoint = CreateCurrentProtocolEndpoint(underProtoclEndpoint);

            for (int i = 0; i < endPointPairs.Count; i++)
            {
                if (endPointPairs[i].UnderProtocolEndpoint.Equals(underProtoclEndpoint))
                {
                    throw new InvalidOperationException("The endpoint is existed.");
                }
            }

            endPointPairs.Add(endpointPair);

            return(endpointPair.CurrentProtocolEndpoint);
        }
        //###########################################################################################
        /// <summary>
        /// Connection to the distant host. Close the socket if it's already connected.
        /// </summary>
        /// <returns></returns>
        private async Task Connect()
        {
            if (_connected)
            {
                Close();
            }

            // check the local ip for creating EndpointPair that link the socket and the distant host
            var local_ip = LocalIp();
            var endpoint = new EndpointPair(new HostName(local_ip), _port, _host, _port);

            // build the link and get the output strem for sending message
            await _socket.ConnectAsync(endpoint);

            _outStream = _socket.OutputStream.AsStreamForWrite();

            // try to connect
            await ConnectRequest();
        }
示例#12
0
        static void Main(string[] args)
        {
            var sensor = Sensor.GetDefaultAsync().AsTask().Result;

            // TODO: rewrite using async/await

            sensor.AllowRemoteClient = true;
            sensor.OpenAsync().AsTask().Wait();

            Console.WriteLine($"Kinect sensor running in {sensor.Type} mode");

            var remoteEndPoint = new EndpointPair(null, string.Empty, new HostName("127.0.0.1"), "8599");
            var clientSensor   = Sensor.CreateNetworkSensor(remoteEndPoint);

            Console.WriteLine($"Kinect sensor 2 set-up in {clientSensor.Type} mode");
            clientSensor.OpenAsync().AsTask().Wait();

            Console.WriteLine($"Kinect sensor 2 IsActive: {clientSensor.IsActive}");
            Console.ReadLine();
            Console.ReadLine();
        }
        /// <summary>
        /// Establishes a socket connection to the specified host and port.
        /// </summary>
        /// <param name="host">The host name of the server to connect to.</param>
        /// <param name="port">The port to connect to.</param>
        /// <exception cref="SshOperationTimeoutException">The connection failed to establish within the configured <see cref="Renci.SshNet.ConnectionInfo.Timeout"/>.</exception>
        /// <exception cref="SocketException">An error occurred trying to establish the connection.</exception>
        partial void SocketConnect(string host, int port)
        {
            const int socketBufferSize = 2 * MaximumSshPacketSize;

            var timeout = ConnectionInfo.Timeout;
            var ep      = new EndpointPair(null, string.Empty, new HostName(host), port.ToString());

            _socket = new SocketWrapper();
            _socket.Control.NoDelay = true;
            _socket.Control.OutboundBufferSizeInBytes = socketBufferSize;

            Log(string.Format("Initiating connect to '{0}:{1}'.", ConnectionInfo.Host, ConnectionInfo.Port));

            var connectResult = _socket.ConnectAsync(ep).AsTask();

            if (Task.WhenAny(connectResult, Task.Delay(timeout)).Result != connectResult)
            {
                throw new SshOperationTimeoutException(string.Format(CultureInfo.InvariantCulture,
                                                                     "Connection failed to establish within {0:F0} milliseconds.", timeout.TotalMilliseconds));
            }
        }
示例#14
0
        public Connection(string remoteHost, int port, IRTSessionInternal session)
        {
            emptyStream.Wrap(new BinaryWriteMemoryStream());
            this.session = session;

#if __WINDOWS__
            try
            {
                Task <EndpointPair> t = Task.Run <EndpointPair>(() => ResolveDNS(remoteHost, port));

                t.Wait();

                endPoint = t.Result;
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex);
            }
#else
            GSInstance instance = session.GetGSInstance();
            ResolveRemoteEndpoint(remoteHost, port);
        }
示例#15
0
        private async Task <bool> Connect(EndpointPair epair)
        {
            if (socket != null)
            {
                try
                {
                    await socket.ConnectAsync(epair);

                    dataReader = new DataReader(socket.InputStream);
                    dataReader.InputStreamOptions = InputStreamOptions.Partial;
#pragma warning disable 4014
                    Task.Run(() => { ReceiveMessages(); });
#pragma warning restore 4014
                    dataWriter = new DataWriter(socket.OutputStream);
                    return(true);
                }
                catch (Exception)
                {
                }
            }

            return(false);
        }
示例#16
0
        public Task <string> ConnectAsync(EndpointPair Endpoint = null, ConnectionInformationObject connectionInfo = null)
        {
            return(Task.Run(async() =>
            {
                if (Endpoint == null && this.ep != null)
                {
                    Endpoint = this.ep;
                }
                else
                {
                    throw new ArgumentNullException("Endpoint", "EndpointPair param is null");
                }

                await clientSocket.ConnectAsync(ep.RemoteHostName, ep.RemoteServiceName);
                writer = new DataWriter(clientSocket.OutputStream);
                reader = new DataReader(clientSocket.InputStream);


                await SendCommandAsync("connect:" + connectionInfo.UserID + ":" + connectionInfo.UserAlias + ":" + connectionInfo.Administrator + ":" + connectionInfo.ChatRoomID);
                string response = await ReadAsync();

                return response;
            }));
        }
        private async Task <bool> Connect(EndpointPair epair)
        {
            if (this.socket != null)
            {
                try
                {
                    await this.socket.ConnectAsync(epair);

                    this.dataReader = new DataReader(this.socket.InputStream);
                    this.dataReader.InputStreamOptions = InputStreamOptions.Partial;
#pragma warning disable 4014
                    Task.Run(() => { this.ReceiveMessages(); });
#pragma warning restore 4014
                    this.dataWriter = new DataWriter(this.socket.OutputStream);
                    return(true);
                }
                catch (Exception)
                {
                    // multiple messages across protocols, all valid for not connecting
                }
            }

            return(false);
        }
示例#18
0
        private async void OnConnectionRequested(WiFiDirectConnectionListener listener, WiFiDirectConnectionRequestedEventArgs eventArgs)
        {
            if (_listener != null)
            {
                _listener.LogMessage("Connection Requested...");
            }
            bool acceptConnection = true;

            if (!AutoAccept && _prompt != null)
            {
                acceptConnection = _prompt.AcceptIncommingConnection();
            }

            try
            {
                WiFiDirectConnectionRequest request = eventArgs.GetConnectionRequest();
                if (acceptConnection)
                {
                    DeviceInformation deviceInformation = request.DeviceInformation;
                    string            deviceId          = deviceInformation.Id;

                    // Must call FromIdAsync first
                    var tcsWiFiDirectDevice = new TaskCompletionSource <WiFiDirectDevice>();
                    var wfdDeviceTask       = tcsWiFiDirectDevice.Task;
                    tcsWiFiDirectDevice.SetResult(await WiFiDirectDevice.FromIdAsync(deviceId));
                    // Get the WiFiDirectDevice object
                    WiFiDirectDevice wfdDevice = await wfdDeviceTask;

                    // Now retrieve the endpoint pairs, which includes the IP address assigned to the peer
                    var    endpointPairs  = wfdDevice.GetConnectionEndpointPairs();
                    string remoteHostName = "";
                    if (endpointPairs.Any())
                    {
                        EndpointPair endpoint = endpointPairs[0];
                        remoteHostName = endpoint.RemoteHostName.DisplayName;
                    }
                    else
                    {
                        throw new Exception("Can't retrieve endpoint pairs");
                    }

                    // Add handler for connection status changed
                    wfdDevice.ConnectionStatusChanged += OnConnectionStatusChanged;

                    // Store the connected peer
                    lock (_threadObject)
                    {
                        _connectedDevices.Add(wfdDevice.DeviceId, wfdDevice);
                    }

                    // Notify Listener
                    if (_listener != null)
                    {
                        _listener.OnDeviceConnected(remoteHostName);
                    }
                }
                else
                {
                    if (_listener != null)
                    {
                        _listener.LogMessage("Declined");
                    }
                }
            }
            catch (Exception ex)
            {
                if (_listener != null)
                {
                    _listener.OnAsyncException(ex.ToString());
                }
                return;
            }
        }
        async void Connect(object sender, RoutedEventArgs e)
        {
            rootPage.NotifyUser("", NotifyType.ErrorMessage);
            DeviceInformation chosenDevInfo = null;
            EndpointPair      endpointPair  = null;

            try
            {
                // If nothing is selected, return
                if (FoundDevicesList.SelectedIndex == -1)
                {
                    rootPage.NotifyUser("Please select a device", NotifyType.StatusMessage);
                    return;
                }
                else
                {
                    chosenDevInfo = devInfoCollection[FoundDevicesList.SelectedIndex];
                }

                rootPage.NotifyUser("Connecting to " + chosenDevInfo.Name + "(" + chosenDevInfo.Id + ")" + "....", NotifyType.StatusMessage);


                // Connect to the selected WiFiDirect device
                wfdDevice = await Windows.Devices.WiFiDirect.WiFiDirectDevice.FromIdAsync(chosenDevInfo.Id);

                if (wfdDevice == null)
                {
                    rootPage.NotifyUser("Connection to " + chosenDevInfo.Name + " failed.", NotifyType.StatusMessage);
                    return;
                }

                // Register for Connection status change notification
                wfdDevice.ConnectionStatusChanged += new TypedEventHandler <Windows.Devices.WiFiDirect.WiFiDirectDevice, object>(DisconnectNotification);

                // Get the EndpointPair collection
                var EndpointPairCollection = wfdDevice.GetConnectionEndpointPairs();
                if (EndpointPairCollection.Count > 0)
                {
                    endpointPair = EndpointPairCollection[0];
                }
                else
                {
                    rootPage.NotifyUser("Connection to " + chosenDevInfo.Name + " failed.", NotifyType.StatusMessage);
                    return;
                }

                PCIpAddress.Text            = "PC's IP Address: " + endpointPair.LocalHostName.ToString();
                DeviceIpAddress.Text        = "Device's IP Address: " + endpointPair.RemoteHostName.ToString();
                PCIpAddress.Visibility      = Visibility.Visible;
                DeviceIpAddress.Visibility  = Visibility.Visible;
                DisconnectButton.Visibility = Visibility.Visible;
                ConnectButton.Visibility    = Visibility.Collapsed;
                FoundDevicesList.Visibility = Visibility.Collapsed;
                GetDevicesButton.Visibility = Visibility.Collapsed;

                rootPage.NotifyUser("Connection succeeded", NotifyType.StatusMessage);
            }
            catch (Exception err)
            {
                rootPage.NotifyUser("Connection to " + chosenDevInfo.Name + " failed: " + err.Message, NotifyType.ErrorMessage);
            }
        }
示例#20
0
        async void Connect(object sender, RoutedEventArgs e)
        {
            rootPage.NotifyUser("", NotifyType.ErrorMessage);
            DeviceInformation chosenDevInfo = null;
            EndpointPair      endpointPair  = null;

            try
            {
                // If nothing is selected, return
                if (FoundDevicesList.SelectedIndex == -1)
                {
                    rootPage.NotifyUser("Please select a device", NotifyType.StatusMessage);
                    return;
                }
                else
                {
                    chosenDevInfo = devInfoCollection[FoundDevicesList.SelectedIndex];
                }

                rootPage.NotifyUser("Connecting to " + chosenDevInfo.Name + "....", NotifyType.StatusMessage);


                // Connect to the selected WiFiDirect device
                wfdDevice = await Windows.Devices.WiFiDirect.WiFiDirectDevice.FromIdAsync(chosenDevInfo.Id);

                if (wfdDevice == null)
                {
                    rootPage.NotifyUser("Connection to " + chosenDevInfo.Name + " failed.", NotifyType.StatusMessage);
                    return;
                }

                // Register for Connection status change notification
                wfdDevice.ConnectionStatusChanged += new TypedEventHandler <Windows.Devices.WiFiDirect.WiFiDirectDevice, object>(DisconnectNotification);

                // Get the EndpointPair collection
                var EndpointPairCollection = wfdDevice.GetConnectionEndpointPairs();
                if (EndpointPairCollection.Count > 0)
                {
                    endpointPair = EndpointPairCollection[0];
                }
                else
                {
                    rootPage.NotifyUser("Connection to " + chosenDevInfo.Name + " failed.", NotifyType.StatusMessage);
                    return;
                }

                PCIpAddress.Text           = "PC's IP Address: " + endpointPair.LocalHostName.ToString();
                DeviceIpAddress.Text       = "Device's IP Address: " + endpointPair.RemoteHostName.ToString();
                PCIpAddress.Visibility     = Visibility.Visible;
                DeviceIpAddress.Visibility = Visibility.Visible;
                //SendTextButton.Visibility = Visibility.Visible;
                DisconnectButton.Visibility = Visibility.Visible;
                ConnectButton.Visibility    = Visibility.Collapsed;
                FoundDevicesList.Visibility = Visibility.Collapsed;
                GetDevicesButton.Visibility = Visibility.Collapsed;

                rootPage.NotifyUser("Connection succeeded", NotifyType.StatusMessage);

                //Server Socket open
                StreamSocketListener listener = new StreamSocketListener();
                listener.ConnectionReceived += OnConnection;

                // Start listen operation.
                try
                {
                    // bind to any
                    // Don't limit traffic to an address or an adapter.
                    await listener.BindServiceNameAsync("9190");

                    rootPage.NotifyUser("Listening", NotifyType.StatusMessage);

                    // bind to specific address
                    // Try to bind to a specific address.
                    //BindEndpointAsync(Target IPAddr, Port Number)
                    //HostName DeviceIPHostName = new HostName(endpointPair.RemoteHostName.ToString());
                    //await listener.BindEndpointAsync(DeviceIPHostName, "9190");
                    //rootPage.NotifyUser(
                    //   "Listening on address " + DeviceIPHostName.ToString(), NotifyType.StatusMessage);
                }
                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;
                    }

                    rootPage.NotifyUser(
                        "Start listening failed with error: " + exception.Message, NotifyType.ErrorMessage);
                }
            }
            catch (Exception err)
            {
                rootPage.NotifyUser("Connection to " + chosenDevInfo.Name + " failed: " + err.Message, NotifyType.ErrorMessage);
            }
        }
示例#21
0
        /// <summary>
        /// Internal constructor for UDP connections
        /// </summary>
        /// <param name="connectionInfo"></param>
        /// <param name="defaultSendReceiveOptions"></param>
        /// <param name="level"></param>
        /// <param name="listenForIncomingPackets"></param>
        /// <param name="existingConnection"></param>
        internal UDPConnection(ConnectionInfo connectionInfo, SendReceiveOptions defaultSendReceiveOptions, UDPOptions level, bool listenForIncomingPackets, UDPConnection existingConnection = null)
            : base(connectionInfo, defaultSendReceiveOptions)
        {
            if (connectionInfo.ConnectionType != ConnectionType.UDP)
            {
                throw new ArgumentException("Provided connectionType must be UDP.", "connectionInfo");
            }

            if (NetworkComms.LoggingEnabled)
            {
                NetworkComms.Logger.Trace("Creating new UDPConnection with " + connectionInfo);
            }

            if (connectionInfo.ApplicationLayerProtocol == ApplicationLayerProtocolStatus.Disabled && level != UDPOptions.None)
            {
                throw new ArgumentException("If the application layer protocol has been disabled the provided UDPOptions can only be UDPOptions.None.");
            }

            ConnectionUDPOptions = level;

            if (listenForIncomingPackets && existingConnection != null)
            {
                throw new Exception("Unable to listen for incoming packets if an existing client has been provided. This is to prevent possible multiple accidently listens on the same client.");
            }

            if (existingConnection == null)
            {
                if (connectionInfo.RemoteIPEndPoint.Address.Equals(IPAddress.Any) || connectionInfo.RemoteIPEndPoint.Address.Equals(IPAddress.IPv6Any))
                {
#if WINDOWS_PHONE || NETFX_CORE
                    //We are creating an unbound endPoint, this is currently the rogue UDP sender and listeners only
                    socket = new DatagramSocket();

                    if (listenForIncomingPackets)
                    {
                        socket.MessageReceived += socket_MessageReceived;
                    }

                    socket.BindEndpointAsync(new HostName(ConnectionInfo.LocalIPEndPoint.Address.ToString()), ConnectionInfo.LocalIPEndPoint.Port.ToString()).AsTask().Wait();
#else
                    //We are creating an unbound endPoint, this is currently the rogue UDP sender and listeners only
                    udpClient = new UdpClientWrapper(new UdpClient(ConnectionInfo.LocalIPEndPoint));
#endif
                }
                else
                {
                    //If this is a specific connection we link to a default end point here
                    isIsolatedUDPConnection = true;

#if WINDOWS_PHONE || NETFX_CORE
                    if (ConnectionInfo.LocalEndPoint == null ||
                        (ConnectionInfo.LocalIPEndPoint.Address == IPAddress.Any && connectionInfo.LocalIPEndPoint.Port == 0) ||
                        (ConnectionInfo.LocalIPEndPoint.Address == IPAddress.IPv6Any && connectionInfo.LocalIPEndPoint.Port == 0))
                    {
                        socket = new DatagramSocket();

                        if (listenForIncomingPackets)
                        {
                            socket.MessageReceived += socket_MessageReceived;
                        }

                        socket.ConnectAsync(new HostName(ConnectionInfo.RemoteIPEndPoint.Address.ToString()), ConnectionInfo.RemoteIPEndPoint.Port.ToString()).AsTask().Wait();
                    }
                    else
                    {
                        socket = new DatagramSocket();

                        if (listenForIncomingPackets)
                        {
                            socket.MessageReceived += socket_MessageReceived;
                        }

                        EndpointPair pair = new EndpointPair(new HostName(ConnectionInfo.LocalIPEndPoint.Address.ToString()), ConnectionInfo.LocalIPEndPoint.Port.ToString(),
                                                             new HostName(ConnectionInfo.RemoteIPEndPoint.Address.ToString()), ConnectionInfo.RemoteIPEndPoint.Port.ToString());

                        socket.ConnectAsync(pair).AsTask().Wait();
                    }
#else
                    if (ConnectionInfo.LocalEndPoint == null)
                    {
                        udpClient = new UdpClientWrapper(new UdpClient(ConnectionInfo.RemoteEndPoint.AddressFamily));
                    }
                    else
                    {
                        udpClient = new UdpClientWrapper(new UdpClient(ConnectionInfo.LocalIPEndPoint));
                    }

                    //By calling connect we discard packets from anything other then the provided remoteEndPoint on our localEndPoint
                    udpClient.Connect(ConnectionInfo.RemoteIPEndPoint);
#endif
                }

#if !WINDOWS_PHONE && !NETFX_CORE
                //NAT traversal does not work in .net 2.0
                //Mono does not seem to have implemented AllowNatTraversal method and attempting the below method call will throw an exception
                //if (Type.GetType("Mono.Runtime") == null)
                //Allow NAT traversal by default for all udp clients
                //    udpClientThreadSafe.AllowNatTraversal(true);

                if (listenForIncomingPackets)
                {
                    StartIncomingDataListen();
                }
#endif
            }
            else
            {
                if (!existingConnection.ConnectionInfo.RemoteIPEndPoint.Address.Equals(IPAddress.Any))
                {
                    throw new Exception("If an existing udpClient is provided it must be unbound to a specific remoteEndPoint");
                }

#if WINDOWS_PHONE || NETFX_CORE
                //Using an exiting client allows us to send from the same port as for the provided existing connection
                this.socket = existingConnection.socket;
#else
                //Using an exiting client allows us to send from the same port as for the provided existing connection
                this.udpClient = existingConnection.udpClient;
#endif
            }

            IPEndPoint localEndPoint;
#if WINDOWS_PHONE || NETFX_CORE
            localEndPoint = new IPEndPoint(IPAddress.Parse(socket.Information.LocalAddress.DisplayName.ToString()), int.Parse(socket.Information.LocalPort));
#else
            localEndPoint = udpClient.LocalIPEndPoint;
#endif

            //We can update the localEndPoint so that it is correct
            if (!ConnectionInfo.LocalEndPoint.Equals(localEndPoint))
            {
                //We should now be able to set the connectionInfo localEndPoint
                NetworkComms.UpdateConnectionReferenceByEndPoint(this, ConnectionInfo.RemoteIPEndPoint, localEndPoint);
                ConnectionInfo.UpdateLocalEndPointInfo(localEndPoint);
            }
        }
示例#22
0
 public void SetEndpoint(RTCConnectionObject rtcObject)
 {
     ep          = rtcObject.Endpoint;
     endpointSet = true;
 }
示例#23
0
 public RTCConnectionObject()
 {
     //ResolveServerHost();
     ep = new EndpointPair(new HostName("localhost"), port, new HostName(host), port);
 }
示例#24
0
 private Sensor(EndpointPair remoteEndPoint)
 {
     _sensorAddress = remoteEndPoint;
     Type           = SensorType.NetworkClient;
 }
示例#25
0
 public static Sensor CreateNetworkSensor(EndpointPair remoteEndPoint)
 {
     return(new Sensor(remoteEndPoint));
 }