当前位置: 首页>>代码示例>>C#>>正文


C# UdpClient.Connect方法代码示例

本文整理汇总了C#中System.Net.Sockets.UdpClient.Connect方法的典型用法代码示例。如果您正苦于以下问题:C# UdpClient.Connect方法的具体用法?C# UdpClient.Connect怎么用?C# UdpClient.Connect使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在System.Net.Sockets.UdpClient的用法示例。


在下文中一共展示了UdpClient.Connect方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: SendAndReceivePacket

		public async Task<RadiusPacket> SendAndReceivePacket(RadiusPacket packet, int retries = DEFAULT_RETRIES)
		{
			using (UdpClient udpClient = new UdpClient())
			{
				udpClient.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, _SocketTimeout);

				try
				{
					IPAddress hostIP;

					if (IPAddress.TryParse(_HostName, out hostIP))
						udpClient.Connect(hostIP, (int) _AuthPort);
					else
						udpClient.Connect(_HostName, (int) _AuthPort);
					
				}
				catch (SocketException e)
				{
					int hr = Marshal.GetHRForException(e);
					string hexValue = hr.ToString("X");

					//The requested name is valid, but no data of the requested type was found
					if (hexValue == "80004005")
						return null;
				}

				var endPoint = (IPEndPoint)udpClient.Client.RemoteEndPoint;

				int numberOfAttempts = 0;

				do
				{
					await udpClient.SendAsync(packet.RawData, packet.RawData.Length);

					try
					{
						// Using the synchronous method for the timeout features
						var result = udpClient.Receive(ref endPoint);
						RadiusPacket receivedPacket = new RadiusPacket(result);

						if (receivedPacket.Valid && VerifyAuthenticator(packet, receivedPacket))
							return receivedPacket;
					}
					catch (SocketException)
					{
						//Server isn't responding
					}

					numberOfAttempts++;

				} while (numberOfAttempts < retries);
			}

			return null;
		}
开发者ID:QANTau,项目名称:Radius.NET,代码行数:55,代码来源:RadiusClient.cs

示例2: OnStart

        public void OnStart()
        {
            try
            {
                udpClient = new UdpClient();

                string ip = Conf.GetSetting<string>("EnttecIP");
                Log.DebugFormat("Connect Enttec on {0}", ip);

                // Ports: 6454 = Artnet, 3333  = ESP
                //IPEndPoint ep = new IPEndPoint(IPAddress.Parse("192.168.0.10"), 6454);
                //IPEndPoint ep = new IPEndPoint(IPAddress.Parse("172.22.25.40"), 6454);
                IPEndPoint ep = new IPEndPoint(IPAddress.Parse(ip), 6454);
                udpClient.Connect(ep);

                Log.Info("Started Transmitter " + GetType());
            }
            catch (Exception e)
            {
                Log.Fatal(e);
            }

            try
            {
                EndPointMngr.HostWcfInstance<ITransmitter>(this);
            }
            catch (Exception e)
            {
                Log.Fatal("Could not host service EquipmentManager", e);
            }
        }
开发者ID:Lucasvo1,项目名称:FHVGame,代码行数:31,代码来源:TransmitterEnttec.cs

示例3: GetServers

        public async Task<IEnumerable<Server>> GetServers(
            MasterServerRegion region = MasterServerRegion.All,
            params MasterServerFilter[] masterServerFilters)
        {
            var servers = new List<Server>();

            using (var client = new UdpClient(new IPEndPoint(IPAddress.Any, 0)))
            {
                client.Connect(_steamSteamIpAddress, _steamSteamPort);

                string thisServer = null;
                while (thisServer != FIRST_AND_LAST_SERVER)
                {
                    var requestPacket = CreateRequestPacket(thisServer ?? FIRST_AND_LAST_SERVER, region, masterServerFilters);
                    await client.SendAsync(requestPacket, requestPacket.Length);
                    var response = await client.ReceiveAsync();
                    var responseData = response.Buffer.ToList();
                    for (int i = HEADER_BYTES_LENGTH; i < responseData.Count; i++)
                    {
                        var ip = string.Join(".", responseData.GetRange(i, 4).ToArray());
                        int port = responseData[i + 4] << 8 | responseData[i + 5];
                        thisServer = string.Format("{0}:{1}", ip, port);
                        if (thisServer != FIRST_AND_LAST_SERVER)
                        {
                            servers.Add(new Server(new IPEndPoint(IPAddress.Parse(ip), port)));
                        }
                        i += 5;
                    }
                }
            }

            return servers;
        }
开发者ID:griha41,项目名称:Steam.Query,代码行数:33,代码来源:MasterServer.cs

示例4: Connect

        private void Connect(IPEndPoint endPoint, int inputDeviceNumber, INetworkChatCodec codec)
        {
            waveIn = new WaveIn();
            waveIn.BufferMilliseconds = 50;
            waveIn.DeviceNumber = inputDeviceNumber;
            waveIn.WaveFormat = codec.RecordFormat;
            waveIn.DataAvailable += waveIn_DataAvailable;
            waveIn.StartRecording();

            udpSender = new UdpClient();
            udpListener = new UdpClient();

            // To allow us to talk to ourselves for test purposes:
            // http://stackoverflow.com/questions/687868/sending-and-receiving-udp-packets-between-two-programs-on-the-same-computer
            udpListener.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
            udpListener.Client.Bind(endPoint);

            udpSender.Connect(endPoint);

            waveOut = new WaveOut();
            waveProvider = new BufferedWaveProvider(codec.RecordFormat);
            waveOut.Init(waveProvider);
            waveOut.Play();

            connected = true;
            var state = new ListenerThreadState { Codec = codec, EndPoint = endPoint };
            ThreadPool.QueueUserWorkItem(ListenerThread, state);
        }
开发者ID:LibertyLocked,项目名称:NAudio,代码行数:28,代码来源:NetworkChatPanel.cs

示例5: StatsDClient

 public StatsDClient(string hostname, int port, string keyPrefix = null)
 {
     _keyPrefix = keyPrefix;
     _client = new UdpClient { ExclusiveAddressUse = false };
     _client.Connect(hostname, port);
     _random = new Random();
 }
开发者ID:jarriett,项目名称:Graphite.NET,代码行数:7,代码来源:StatsDClient.cs

示例6: buttonApply_Click

 private void buttonApply_Click(object sender, EventArgs e)
 {
     UdpClient udpClient = new UdpClient();
     udpClient.Connect(TextBoxIPComputer.Text, SERVER_PORT);
     Byte[] senddata = Encoding.ASCII.GetBytes("sync " + DateTime.UtcNow.ToString());
     udpClient.Send(senddata, senddata.Length);
 }
开发者ID:pvn1981,项目名称:SystemTools,代码行数:7,代码来源:FormMain.cs

示例7: GetServerChallengeSync

        public ServerPlayers GetServerChallengeSync(GetServerInfoSettings settings)
        {
            var localEndpoint = new IPEndPoint(IPAddress.Any, 0);
            using (var client = new UdpClient(localEndpoint))
            {
                client.Client.ReceiveTimeout = settings.ReceiveTimeout;
                client.Client.SendTimeout = settings.SendTimeout;

                client.Connect(EndPoint);

                var requestPacket = new List<byte>();
                requestPacket.AddRange(new Byte[] { 0xFF, 0xFF, 0xFF, 0xFF, 0x55 });
                requestPacket.AddRange(BitConverter.GetBytes(-1));

                client.Send(requestPacket.ToArray(), requestPacket.ToArray().Length);
                byte[] responseData = client.Receive(ref localEndpoint);
                requestPacket.Clear();
                requestPacket.AddRange(new Byte[] { 0xFF, 0xFF, 0xFF, 0xFF, 0x55 });
                requestPacket.AddRange(responseData.Skip(5).Take(4));
                client.Send(requestPacket.ToArray(), requestPacket.ToArray().Length);
                responseData = client.Receive(ref localEndpoint);

                return ServerPlayers.Parse(responseData);
            }
        }
开发者ID:svargy,项目名称:arma3beclient,代码行数:25,代码来源:Server.cs

示例8: Connect

        public Task Connect()
        {
            _socket = BuildSocket(new IPEndPoint(_ipAddress, _settings.CommandPort));
            _socket.Connect(new IPEndPoint(IPAddress.Parse(_settings.WifiLinkIpAddress), _settings.CommandPort));

            return Pair();
        }
开发者ID:jamesleech,项目名称:Harmonize,代码行数:7,代码来源:CommandEndpoint.cs

示例9: Main

        static void Main(string[] args)
        {
            IPAddress[] ip_addresses;
            IPEndPoint ip_end_point;
            UdpClient udp_client;
            byte[] mac_bytes;

            test();

            //verify arg[0] is valid MAC address
            if (!validate_args(args))
            {
                show_help();
                return;
            }

            mac_bytes = convert_mac_address(args[0]);

            ip_addresses = Dns.GetHostAddresses(Dns.GetHostName());
            foreach (IPAddress ip_address in ip_addresses)
            {
                if (IPAddress.IsLoopback(ip_address) || ip_address.AddressFamily != AddressFamily.InterNetwork) continue;
                ip_end_point = new IPEndPoint(ip_address, 0);
                udp_client = new UdpClient(ip_end_point);
                udp_client.Connect(IPAddress.Broadcast, 80);
                byte[] data = magic_packet_bytes(mac_bytes);
                udp_client.Send(data, data.Length);
            }
        }
开发者ID:phonegi,项目名称:network,代码行数:29,代码来源:Program.cs

示例10: UDPClient

 public UDPClient(IPEndPoint endPoint)
 {
     Internal = new UdpClient(endPoint);
     this.IP = endPoint.Address;
     this.Port = endPoint.Port;
     Internal.Connect(endPoint);
 }
开发者ID:sathley,项目名称:Market-Data-Dissemination,代码行数:7,代码来源:UDPClient.cs

示例11: GetExternalAddress

        public static IPAddress GetExternalAddress()
        {
            IPHostEntry entry = Dns.GetHostEntry (stunServer);
            IPEndPoint endPoint = new IPEndPoint (entry.AddressList [0], 3478);
            UdpClient client = new UdpClient ();
            client.Connect (endPoint);

            MessageHeader header = new MessageHeader ();
            header.MessageType = MessageType.BindingRequest;

            byte[] bytes = header.GetBytes ();
            client.Send (bytes, bytes.Length);

            bytes = client.Receive (ref endPoint);

            header = new MessageHeader (bytes);
            if (header.MessageType == MessageType.BindingResponse) {
                foreach (MessageAttribute attribute in header.MessageAttributes) {
                    if (attribute is MappedAddressAttribute) {
                        return (attribute as AddressAttributeBase).Address;
                    }
                }
                throw new Exception ("Resposne was missing Mapped-address!");
            } else {
                throw new Exception ("Wrong response message!");
            }
        }
开发者ID:codebutler,项目名称:meshwork,代码行数:27,代码来源:StunClient.cs

示例12: CheckIsOpenPort

        public bool CheckIsOpenPort(string ip, int port)
        {
            string log = string.Empty;

            System.Net.IPAddress myIpAddress = IPAddress.Parse(ip);
            System.Net.IPEndPoint myIpEndPoint = new IPEndPoint(myIpAddress, 8000);

            try
            {
                System.Net.Sockets.TcpClient tcpClient = new TcpClient();
                tcpClient.Connect(myIpEndPoint);//对远程计算机的指定端口提出TCP连接请求
                tcpClient.Close();

                Console.WriteLine("IP为{0}的计算机{1}端口开放了TCP服务!!!", ip, port);
                return true;
            }
            catch { }
            try
            {
                System.Net.Sockets.UdpClient udpClient = new UdpClient();
                udpClient.Connect(myIpEndPoint);//对远程计算机的指定端口提出UDP连接请求
                udpClient.Close();

                Console.WriteLine("IP为{0}的计算机{1}端口开放了UDP服务!!!", ip, port);
                return true;
            }
            catch
            {

            }
            return false;
        }
开发者ID:romanu6891,项目名称:fivemen,代码行数:32,代码来源:ComputerMonitorHelper.cs

示例13: Send

 internal int Send(DateTime timestamp, string hostname, string message)
 {
     string s = string.Format("<{0}>1 {1} {2} {3}", new object[]
     {
         this.Facility * 8 + this.Severity,
         timestamp.ToString("yyyy-MM-ddTHH:mm:ss.fffZ"),
         hostname,
         message
     });
     int result;
     try
     {
         IPEndPoint endPoint = new IPEndPoint(IPAddress.Parse(this.Server), this.Port);
         UdpClient udpClient = new UdpClient();
         udpClient.Connect(endPoint);
         byte[] bytes = Encoding.ASCII.GetBytes(s);
         udpClient.Send(bytes, bytes.Length);
         result = 0;
     }
     catch
     {
         result = 1;
     }
     return result;
 }
开发者ID:postfix,项目名称:uprootd,代码行数:25,代码来源:Syslog.cs

示例14: Index

        public string Index(string id)
        {
            try {
                // Convert MAC address to Hex bytes
                var value = long.Parse(id.Replace("-", "").Replace(":", ""), NumberStyles.HexNumber, CultureInfo.CurrentCulture.NumberFormat);
                var macBytes = BitConverter.GetBytes(value);
                Array.Reverse(macBytes);

                var macAddress = new byte[6];
                for (int i = 0; i <= 5; i++)
                    macAddress[i] = macBytes[i + 2];

                var packet = new List<byte>();

                //Trailer of 6 FF packets
                for (int i = 0; i < 6; i++)
                    packet.Add(0xFF);

                //Repeat 16 time the MAC address (which is 6 bytes)
                for (int i = 0; i < 16; i++)
                    packet.AddRange(macAddress);

                var client = new UdpClient();
                client.Connect(IPAddress.Broadcast, 7); //the port doesn't matter
                client.Send(packet.ToArray(), packet.Count);

                return "";
            }
            catch (Exception ex) {
                return ex.Message;
            }
        }
开发者ID:saxx,项目名称:WolWeb,代码行数:32,代码来源:WakeController.cs

示例15: Main

        static void Main(string[] args)
        {
            IPEndPoint remoteIpEndPoint = new IPEndPoint(IPAddress.Any, 0);
            udpClient = new UdpClient(10101);
            byte[] buffer;
            Thread tread = new Thread(() => sendPoints());
            tread.Start();
            while( true )
            {
                buffer = udpClient.Receive(ref remoteIpEndPoint);

                {
                    foreach (var el in buffer)
                        System.Console.Write((char)el);
                    if( buffer[0] == 'c' )
                    {
                        UdpClient udpClientt = new UdpClient();
                        udpClientt.Connect(remoteIpEndPoint.Address, 10102);
                        byte[] msg = { 0, clientId++ };
                        Thread.Sleep(100);
                        udpClientt.Send( msg, 2);
                        udpClientt.Close();
                        Thread tr = new Thread(() => manageClient(clientId));
                        tr.Start();
                    }
                }

                System.Console.WriteLine();
            }
        }
开发者ID:ptanski,项目名称:PROJEKT_OJP_CS,代码行数:30,代码来源:Program.cs


注:本文中的System.Net.Sockets.UdpClient.Connect方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。