コード例 #1
0
ファイル: RadiusClient.cs プロジェクト: QANTau/Radius.NET
		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;
		}
コード例 #2
0
ファイル: TransmitterEnttec.cs プロジェクト: Lucasvo1/FHVGame
        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);
            }
        }
コード例 #3
0
        public System.Int32 aquariumService_getBrightness()
        {
            Console.WriteLine("[UPnP] Get Brightness");
            var client = new UdpClient();
            IPEndPoint ep = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 5000);
            client.Connect(ep);

            // send data
            Byte[] data = Encoding.ASCII.GetBytes("getLight#0");
            client.Send(data, data.Length);

            var receivedData = client.Receive(ref ep);
            String value = Encoding.ASCII.GetString(receivedData);
            Console.Write("[UPnP] Get Brightness | Value : " + value);

            String s = value.Split('#')[1];
            System.Int32 result = 0;
            try
            {
                float o = float.Parse(s);
                result = Convert.ToInt32(o);
            }
            catch (Exception)
            {
            }


            client.Close();

            return result;
        }
コード例 #4
0
ファイル: Program.cs プロジェクト: ptanski/PROJEKT_OJP_CS
        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();
            }
        }
コード例 #5
0
        /// <summary>
        /// Попытка подключения к серверу
        /// </summary>
        /// <param name="name"></param>
        /// <param name="myPort"></param>
        /// <param name="remotePort"></param>
        /// <param name="remoteIpAddress"></param>
        public void ConnectToServer(string name, string myPort, string remotePort, string remoteIpAddress)
        {
            this.myPort = Convert.ToInt32(myPort);
            this.remotePort = Convert.ToInt32(remotePort);
            sender = new UdpClient(this.myPort);
            this.remoteIPAddress = IPAddress.Parse(remoteIpAddress);
            endPoint = new IPEndPoint(this.remoteIPAddress, this.remotePort);
            myPlayer = new HumanPlayer(name);

            DelegatesData.HandlerPlayerIsMoreThanEnough =
                new DelegatesData.PlayerIsMoreThanEnough(TurnComesToNextPlayer);

            try
            {
                sender.Connect(endPoint); 
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                return;
            }

            Thread thread = new Thread(Listener);
            thread.IsBackground = true;
            thread.Start();
        }
コード例 #6
0
        private async Task SendWakeOnLan(string macAddress, IPEndPoint endPoint, CancellationToken cancellationToken)
        {
            const int payloadSize = 102;

            var macBytes = PhysicalAddress.Parse(macAddress).GetAddressBytes();
            _logger.Debug(String.Format("Sending magic packet to {0}", macAddress));

            // Construct magic packet
            var payload = new byte[payloadSize];
            Buffer.BlockCopy(new byte[] { 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF }, 0, payload, 0, 6);

            for (var i = 1; i < 17; i++) 
            { 
                Buffer.BlockCopy(macBytes, 0, payload, 6 * i, 6);
            }

            // Send packet LAN
            using (var udp = new UdpClient())
            {
                udp.Connect(endPoint);

                cancellationToken.ThrowIfCancellationRequested();

                await udp.SendAsync(payload, payloadSize).ConfigureAwait(false);
            }
        }
コード例 #7
0
        static void Main(string[] args)
        {
            string data = "";
            byte[] sendBytes = new Byte[1024];
            byte[] rcvPacket = new Byte[1024];
            UdpClient client = new UdpClient();
            IPAddress address = IPAddress.Parse(IPAddress.Broadcast.ToString());
            client.Connect(address, 8008);
            IPEndPoint remoteIPEndPoint = new IPEndPoint(IPAddress.Any, 0);

            Console.WriteLine("Client is Started");
            Console.WriteLine("Type your message");

            while (data != "q")
            {
                data = Console.ReadLine();
                sendBytes = Encoding.ASCII.GetBytes(DateTime.Now.ToString() + " " + data);
                client.Send(sendBytes, sendBytes.GetLength(0));
                rcvPacket = client.Receive(ref remoteIPEndPoint);

                string rcvData = Encoding.ASCII.GetString(rcvPacket);
                Console.WriteLine("Handling client at " + remoteIPEndPoint + " - ");

                Console.WriteLine("Message Received: " + rcvPacket.ToString());
            }
            Console.WriteLine("Close Port Command Sent");  //user feedback
            Console.ReadLine();
            client.Close();  //close connection
        }
コード例 #8
0
ファイル: UdpSocket.cs プロジェクト: huijian142857/Dev_Tools
 private bool Connect(string ip, int port)
 {
     try
     {
         if (port == 0 || ip == "")
         {
             return(false);
         }
         Debug.Log("connect battle udp-server " + ip + ":" + port);
         this.TryCloseSocket();
         IPAddress     ipAddress;
         AddressFamily af;
         bool          ok = Misc.Utils.IPV4ToIPV6(ip, out ipAddress, out af);
         _server_endpoint = new IPEndPoint(ipAddress, port);
         _inner_socket    = new UdpClient();
         _inner_socket.Connect(_server_endpoint);
         _inner_socket.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendBuffer, 1024 * 16);
         _inner_socket.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveBuffer, 1024 * 32);
         this.isConnected = true;
     }
     catch (Exception e)
     {
         this.isConnected = false;
         _inner_socket    = null;
         Debug.Log(e.Message);
         return(false);
     }
     return(true);
 }
コード例 #9
0
ファイル: Program.cs プロジェクト: phonegi/network
        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);
            }
        }
コード例 #10
0
ファイル: SteamAgent.cs プロジェクト: robhol/Steam.Query
        public static UdpClient GetUdpClient(IPEndPoint remote)
        {
            var client = new UdpClient(new IPEndPoint(IPAddress.Any, 0));
            client.Connect(remote);

            return client;
        }
コード例 #11
0
ファイル: StunClient.cs プロジェクト: codebutler/meshwork
        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!");
            }
        }
コード例 #12
0
 public UDPClient(IPEndPoint endPoint)
 {
     Internal = new UdpClient(endPoint);
     this.IP = endPoint.Address;
     this.Port = endPoint.Port;
     Internal.Connect(endPoint);
 }
コード例 #13
0
        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;
        }
コード例 #14
0
        protected override void Loop(CancellationToken token)
        {
            using (var udpClient = new UdpClient(NavdataPort))
            {
                udpClient.Connect(_configuration.DroneHostname, NavdataPort);

                SendKeepAliveSignal(udpClient);

                var droneEp = new IPEndPoint(IPAddress.Any, NavdataPort);
                Stopwatch swKeepAlive = Stopwatch.StartNew();
                Stopwatch swNavdataTimeout = Stopwatch.StartNew();
                while (token.IsCancellationRequested == false &&
                       swNavdataTimeout.ElapsedMilliseconds < NavdataTimeout)
                {
                    if (udpClient.Available > 0)
                    {
                        byte[] data = udpClient.Receive(ref droneEp);
                        var packet = new NavigationPacket
                            {
                                Timestamp = DateTime.UtcNow.Ticks,
                                Data = data
                            };
                        _navigationPacketAcquired(packet);
                        swNavdataTimeout.Restart();
                    }

                    if (swKeepAlive.ElapsedMilliseconds > KeepAliveTimeout)
                    {
                        SendKeepAliveSignal(udpClient);
                        swKeepAlive.Restart();
                    }
                    Thread.Sleep(5);
                }
            }
        }
コード例 #15
0
ファイル: Syslog.cs プロジェクト: postfix/uprootd
 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;
 }
コード例 #16
0
ファイル: Server.cs プロジェクト: svargy/arma3beclient
        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);
            }
        }
コード例 #17
0
ファイル: CbNetwork.cs プロジェクト: jessenic/SharpNetMatch
 public void InitClient(string host, int port)
 {
     Client = new UdpClient(host, port);
     Client.Connect(host, port);
     Client.Send(new byte[] { 0x0, 0x0 }, 2);
     //ClientReadInternal();
 }
コード例 #18
0
ファイル: WOL.cs プロジェクト: Luden/main
        public static void WakeUp(byte[] mac)
        {
            //
            // WOL packet is sent over UDP 255.255.255.0:40000.
            //
            UdpClient client = new UdpClient();
            client.Connect(IPAddress.Broadcast, 40000);

            //
            // WOL packet contains a 6-bytes trailer and 16 times a 6-bytes sequence containing the MAC address.
            //
            byte[] packet = new byte[17 * 6];

            //
            // Trailer of 6 times 0xFF.
            //
            for (int i = 0; i < 6; i++)
                packet[i] = 0xFF;

            //
            // Body of magic packet contains 16 times the MAC address.
            //
            for (int i = 1; i <= 16; i++)
                for (int j = 0; j < 6; j++)
                    packet[i * 6 + j] = mac[j];

            //
            // Submit WOL packet.
            //
            client.Send(packet, packet.Length);
        }
コード例 #19
0
ファイル: FormMain.cs プロジェクト: pvn1981/SystemTools
 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);
 }
コード例 #20
0
        public Task Connect()
        {
            _socket = BuildSocket(new IPEndPoint(_ipAddress, _settings.CommandPort));
            _socket.Connect(new IPEndPoint(IPAddress.Parse(_settings.WifiLinkIpAddress), _settings.CommandPort));

            return Pair();
        }
コード例 #21
0
 // Start is called before the first frame update
 void Start()
 {
     //UdpClientオブジェクトを作成する
     udp = new System.Net.Sockets.UdpClient();
     udp.EnableBroadcast = true;
     udp.Connect(new IPEndPoint(IPAddress.Broadcast, remotePort));
 }
コード例 #22
0
        protected override void Loop(CancellationToken token)
        {
            int sequenceNumber = 1;
            ConcurrentQueueHelper.Flush(_commandQueue);

            using (var udpClient = new UdpClient(CommandPort))
            {
                udpClient.Connect(_configuration.DroneHostname, CommandPort);

                byte[] firstMessage = BitConverter.GetBytes(1);
                udpClient.Send(firstMessage, firstMessage.Length);

                Stopwatch swKeepAlive = Stopwatch.StartNew();
                while (token.IsCancellationRequested == false)
                {
                    ATCommand command;
                    if (_commandQueue.TryDequeue(out command))
                    {
                        byte[] payload = command.CreatePayload(sequenceNumber);

                        Trace.WriteIf((command is COMWDGCommand) == false, Encoding.ASCII.GetString(payload));

                        udpClient.Send(payload, payload.Length);
                        sequenceNumber++;
                        swKeepAlive.Restart();
                    }
                    else if (swKeepAlive.ElapsedMilliseconds > KeepAliveTimeout)
                    {
                        _commandQueue.Enqueue(new COMWDGCommand());
                    }
                    Thread.Sleep(1);
                }
            }
        }
コード例 #23
0
ファイル: SntpClient.cs プロジェクト: goose87/rhino-licensing
	    private void EndGetHostAddress(IAsyncResult asyncResult)
        {
	        var state = (State) asyncResult.AsyncState;
	        try
	        {
	            var addresses = Dns.EndGetHostAddresses(asyncResult);
	            var endPoint = new IPEndPoint(addresses[0], 123);

	            var socket = new UdpClient();
	            socket.Connect(endPoint);
	            socket.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, 500);
	            socket.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendTimeout, 500);
	            var sntpData = new byte[SntpDataLength];
	            sntpData[0] = 0x1B; // version = 4 & mode = 3 (client)

	        	var newState = new State(socket, endPoint, state.GetTime, state.Failure);
	        	var result = socket.BeginSend(sntpData, sntpData.Length, EndSend, newState);
				RegisterWaitForTimeout(newState, result);
	        }
	        catch (Exception)
	        {
                // retry, recursion stops at the end of the hosts
                BeginGetDate(state.GetTime, state.Failure);
	
	        }
	    }
コード例 #24
0
        public static void Listen(IPEndPoint remoteIP)
        {
            var done = false;

            var listener = new UdpClient(remoteIP);
            listener.Connect(remoteIP);
            var groupEP = new IPEndPoint(IPAddress.Any, remoteIP.Port);
            try
            {
                while (!done)
                {
                    Console.WriteLine("Waiting for broadcast..");
                    byte[] bytes = listener.Receive(ref groupEP);
                    string json = EncodingUtility.Decode(bytes);
                    Console.WriteLine("Received broadcast from {0}:{1} :\n {2}\n", groupEP.Address,groupEP.Port, json);
                    var message = JsonHelper.JsonDeserialize<ExchangeAMd>(json);
                    //Do aaync
                    ProcessOrder(message);
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }
            finally
            {
                listener.Close();
            }
        }
コード例 #25
0
 // Use this for initialization
 void Start()
 {
     client = new System.Net.Sockets.UdpClient();
     ep     = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 8000);
     client.Connect(ep);
     InvokeRepeating("sendPos", 0.0f, 0.0167f);
 }
コード例 #26
0
ファイル: Program.cs プロジェクト: shaftware/NetMagic
        private static void BroadcastMagicPacket(PhysicalAddress physicalAddress, IPAddress broadcastIPAddress)
        {
            if (physicalAddress == null) throw new ArgumentNullException(nameof(physicalAddress));

            var physicalAddressBytes = physicalAddress.GetAddressBytes();

            var packet = new byte[17 * 6];

            for (var i = 0; i < 6; i++)
            {
                packet[i] = 0xFF;
            }

            for (var i = 1; i <= 16; i++)
            {
                for (var j = 0; j < 6; j++)
                {
                    packet[i * 6 + j] = physicalAddressBytes[j];
                }
            }

            using (var client = new UdpClient())
            {
                client.Connect(broadcastIPAddress ?? IPAddress.Broadcast, 40000);
                client.Send(packet, packet.Length);
            }
        }
コード例 #27
0
ファイル: UdpConnection.cs プロジェクト: slorion/nlight
		public static IObservable<UdpReceiveResult> CreateListener(IPAddress remoteAddress, int port)
		{
			if (remoteAddress == null) throw new ArgumentNullException(nameof(remoteAddress));
			if (port < 0 || port > 65535) throw new ArgumentOutOfRangeException(nameof(port), port, null);

			IPHostEntry host = Dns.GetHostEntry(Dns.GetHostName());

			var remoteIPBytes = remoteAddress.GetAddressBytes();
			var localAddress =
				host.AddressList.FirstOrDefault(ip =>
				ip.AddressFamily == remoteAddress.AddressFamily
				&& ip.GetAddressBytes().Take(3).SequenceEqual(remoteIPBytes.Take(3)));

			if (localAddress == null)
				throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, Resources.ExceptionMessages.Net_NoInterfaceInSameNetwork, remoteAddress, port));

			var localEndPoint = new IPEndPoint(localAddress, port);
			var remoteEndPoint = new IPEndPoint(remoteAddress, port);

			return Observable.Using(
				() =>
				{
					var client = new UdpClient { ExclusiveAddressUse = false };
					client.Client.Bind(localEndPoint);
					client.Connect(remoteEndPoint.Address, 0);
					return client;
				},
				client => Observable.While(() => client.Client.Connected, Observable.FromAsync(client.ReceiveAsync)));
		}
コード例 #28
0
ファイル: Program.cs プロジェクト: RavenXce/PowerWiFlyII
        static void Main(string[] args)
        {
            UdpClient udpClient = new UdpClient(5500);
            //udpClient.Connect("raaj.homeip.net", 2005);
            udpClient.Connect("192.168.1.8", 2005);
            Byte[] sendBytes = Encoding.ASCII.GetBytes("hello?");
            udpClient.Send(sendBytes, sendBytes.Length);

            //IPEndPoint object will allow us to read datagrams sent from any source.
            IPEndPoint RemoteIpEndPoint = new IPEndPoint(IPAddress.Any, 0);

            // Blocks until a message returns on this socket from a remote host.
            Byte[] receiveBytes = udpClient.Receive(ref RemoteIpEndPoint);
            string returnData = Encoding.ASCII.GetString(receiveBytes);

            // Uses the IPEndPoint object to determine which of these two hosts responded.
            Console.WriteLine("This is the message you received " +
                                         returnData.ToString());
            Console.WriteLine("This message was sent from " +
                                     RemoteIpEndPoint.Address.ToString() +
                                     " on their port number " +
                                     RemoteIpEndPoint.Port.ToString());

            udpClient.Close();
            Console.ReadLine();
        }
コード例 #29
0
        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);
        }
コード例 #30
0
 public void Connect()
 {
     try
     {
         System.Net.IPHostEntry       hostEntry = System.Net.Dns.GetHostEntry(this.TimeServer);
         System.Net.IPEndPoint        endPoint  = new System.Net.IPEndPoint(hostEntry.AddressList[0], 123);
         System.Net.Sockets.UdpClient udpClient = new System.Net.Sockets.UdpClient();
         udpClient.Client.ReceiveTimeout = 3000;
         udpClient.Client.SendTimeout    = 3000;
         udpClient.Connect(endPoint);
         this.Initialize();
         udpClient.Send(this.NTPData, this.NTPData.Length);
         this.NTPData            = udpClient.Receive(ref endPoint);
         this.ReceptionTimestamp = System.DateTime.Now;
         if (!this.IsResponseValid())
         {
             throw new System.Exception("Invalid response from " + this.TimeServer);
         }
     }
     catch (System.Net.Sockets.SocketException ex)
     {
         Log.WriteError("NTPʱ¼ä»ñȡʧ°Ü£º" + ¡¡ex.Message);
         throw new System.Exception(ex.Message);
     }
 }
コード例 #31
0
ファイル: WakeController.cs プロジェクト: saxx/WolWeb
        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;
            }
        }
コード例 #32
0
ファイル: ServiceHost.cs プロジェクト: jdaigle/nsysmon
 private static void StartPerfmonCollectionLoop()
 {
     var counters = new PerformanceCounters("");
     var syslogForwarder = new UdpClient();
     syslogForwarder.Connect(ConfigurationManager.AppSettings["forward_host"], int.Parse(ConfigurationManager.AppSettings["forward_port"]));
     var sw = Stopwatch.StartNew();
     while (true)
     {
         sw.Restart();
         foreach (var counter in counters)
         {
             var nextValue = counter.NextValue();
             var timestamp = DateTime.Now;
             var datagram = GetSyslogDatagram(counter, nextValue, timestamp);
             var bytesSend = syslogForwarder.Send(datagram, datagram.Length);
             log.Debug("Sending " + datagram.Length + " bytes");
             if (bytesSend != datagram.Length)
             {
                 log.ErrorFormat("bytes sent " + bytesSend + " does not equal datagram length " + datagram.Length);
             }
         }
         sw.Stop();
         log.Info(string.Format("Queried {0} counters in {1} ms", counters.Count, sw.Elapsed.TotalMilliseconds));
         Thread.Sleep(10 * 1000);
     }
 }
コード例 #33
0
ファイル: StatsDClient.cs プロジェクト: jarriett/Graphite.NET
 public StatsDClient(string hostname, int port, string keyPrefix = null)
 {
     _keyPrefix = keyPrefix;
     _client = new UdpClient { ExclusiveAddressUse = false };
     _client.Connect(hostname, port);
     _random = new Random();
 }
コード例 #34
0
        private void InitClient()
        {
            _client = new System.Net.Sockets.UdpClient(11000);
            _client.Connect(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 12000));

            //_receiveClient = new System.Net.Sockets.UdpClient(11000);
            receivingUdpClient = new System.Net.Sockets.UdpClient(12000);
        }
コード例 #35
0
 public void Connect()
 {
     if (!IsConnected)
     {
         udpclient.Connect(remoteCLIPE);
         _IsConnected = true;
     }
 }
コード例 #36
0
        public void SendCommand()
        {
            _udpClient.Connect(_hostIp, 9000);
            string cmdToSend = Console.ReadLine();

            Byte[] bytesToSend = Encoding.ASCII.GetBytes(cmdToSend);
            _udpClient.Send(bytesToSend, bytesToSend.Length);
        }
コード例 #37
0
ファイル: HUDPClient.cs プロジェクト: step4u/MiniCRM
 public void Connect()
 {
     if (!IsConnected)
     {
         udpclient.Connect(remoteCLIPE);
         //UDPClientConnectedEvent(this, udpclient.);
         _IsConnected = true;
     }
 }
コード例 #38
0
ファイル: Form1.cs プロジェクト: zhxy323/HUST-BDL-SRC
        //打开socket通信
        private void btnConnect_Click(object sender, EventArgs e)
        {
            System.Net.IPAddress ipaddr = null;
            if (!System.Net.IPAddress.TryParse(this.tbIP.Text, out ipaddr))
            {
                MessageBox.Show("请正确填写IP地址!");
                return;
            }

            int iPort = 0;

            if (!int.TryParse(this.tbPort.Text, out iPort) || iPort <= 0)
            {
                MessageBox.Show("请正确填写端口!");
                return;
            }

            _ipaddrDes = new System.Net.IPEndPoint(ipaddr, iPort);

            if (_udp != null)
            {
                _udp.Close();
                _udp = null;
            }

            _udp = new UdpClient(_portListen);

            try
            {
                _udp.Connect(_ipaddrDes);
            }
            catch (System.ObjectDisposedException)
            {
                MessageBox.Show("System.Net.Sockets.UdpClient 已关闭");
                return;
            }
            catch (System.ArgumentOutOfRangeException)
            {
                MessageBox.Show("port 不在 System.Net.IPEndPoint.MinPort 和 System.Net.IPEndPoint.MaxPort 之间");
                return;
            }
            catch (System.Net.Sockets.SocketException ex)
            {
                MessageBox.Show("试图访问套接字时发生错误:" + ex.Message);
                return;
            }
            catch (Exception ex)
            {
                MessageBox.Show("未知类型错误:" + ex.Message);
                return;
            }
            Program.SetAppSettingValue("DefaultIP", this.tbIP.Text);
            Program.SetAppSettingValue("DefaultPortNo", this.tbPort.Text);

            this.btnDisconnect.Enabled = true;
            this.btnConnect.Enabled    = false;
        }
コード例 #39
0
ファイル: UdpClient.cs プロジェクト: SpringSon420/Wms3.0
 public void SendMsg()
 {
     try
     {
         udpSend.Connect(remoteEP);
     }
     catch
     {
         //if (string.IsNullOrEmpty(GblMod.Ins.LoginPerson.UserName)) return;
         E_ServerOnLine?.Invoke("服务器掉线", Color.Red);
         #region DEBUG 待验
         //FrmMain frmMain = g_m as FrmMain;
         //if (frmMain.frmLoginTemp != null)
         //{
         //    MessageBox.Show("连接失败SendMsg" + remoteEP.ToString(), "提示", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
         //}
         //else
         //{
         //MethodInvoker invoker = null;
         //if (frmMain.lblServerOnLine.InvokeRequired)
         //{
         //    if (invokerAgvFirst)
         //    {
         //        invokerAgvFirst = false;
         //        if (invoker == null)
         //        {
         //            invoker = delegate
         //            {
         //                frmMain.lblServerOnLine.BackColor = Color.Red;
         //                frmMain.lblServerOnLine.Text = "服务器掉线";
         //            };
         //        }
         //        offlineAgvInvoker = invoker;
         //    }
         //    else
         //    {
         //        frmMain.lblServerOnLine.Invoke(offlineAgvInvoker);
         //    }
         //}
         //else
         //{
         //    frmMain.lblServerOnLine.BackColor = Color.Red;
         //    frmMain.lblServerOnLine.Text = "服务器掉线";
         //}
         // }
         #endregion
     }
     connectSuccess = true;
     while (!cts.Token.IsCancellationRequested)
     {
         ReceiveMessages();
         Thread.Sleep(30);
     }
 }
コード例 #40
0
ファイル: streamer.cs プロジェクト: elmadjian/GazeBar
    public static void Main(string[] args)
    {
        var host = new Host();

        System.Net.Sockets.UdpClient client = new System.Net.Sockets.UdpClient();
        client.Connect("127.0.0.1", 9998);

        var gazePointDataStream = host.Streams.CreateGazePointDataStream();

        gazePointDataStream.GazePoint((x, y, _) => {
            string message = "g~" + x.ToString() + '~' + y.ToString();
            var datagram   = System.Text.Encoding.ASCII.GetBytes(message);
            client.Send(datagram, datagram.Length);
        });

        Console.ReadKey();
        host.DisableConnection();
    }
コード例 #41
0
        internal UDPNetState(IPEndPoint ep, int readBufferSize)
            : base(ep)
        {
            Reader = new TReader();
            Writer = new TWriter();

            LastActivity = DateTime.UtcNow;

            Client = new UdpClient();
            Client.Connect(ep);
            Writer.SetClient(Client);

            Client.BeginReceive(new AsyncCallback(OnReceived), null);

            Reader.OnDisconnect     += Dispose;
            Reader.OnBufferOverflow += Reader_OnBufferOverflow;

            OnConnected();
        }
コード例 #42
0
        // send thread
        private void SendData()
        {
            System.Net.Sockets.UdpClient cliente = new System.Net.Sockets.UdpClient();



            while (!conectado)
            {
                ;
            }
            cliente.Connect(anyIP.Address, puerto);
            qr.endQRShow();//end the QR
            byte[] timeToVibrate = new byte[4];
            timeToVibrate[0] = (byte)(vibrationTime & 0x000000FF);
            timeToVibrate[1] = (byte)((vibrationTime >> 4) & 0x000000FF);
            timeToVibrate[2] = (byte)((vibrationTime >> 8) & 0x000000FF);
            timeToVibrate[3] = (byte)((vibrationTime >> 16) & 0x000000FF);
            cliente.Send(timeToVibrate, timeToVibrate.Length);


            while (sending)
            {
                if (vibrate)
                {
                    byte[] vibrateMessage = new byte[4];
                    vibrateMessage[0] = 0;
                    vibrateMessage[1] = 0;
                    vibrate           = false;
                    cliente.Send(vibrateMessage, vibrateMessage.Length);
                }
                if (send)
                {
                    send = false;
                    cliente.Send(byteImg, byteImg.Length); //este mensaje tiene de latencia 5ms aprox cuando hace ping
                }
            }
            byte[] sendData = new byte[1];
            //fin de comunicación
            sendData[0] = 1;
            cliente.Send(sendData, sendData.Length);
            Debug.Log("terminó");
        }
コード例 #43
0
ファイル: UdpClientChannel.cs プロジェクト: cdy816/Spider
        /// <summary>
        ///
        /// </summary>
        /// <returns></returns>
        protected override bool InnerOpen()
        {
            mIsClosed = false;

            rp = new System.Net.IPEndPoint(System.Net.IPAddress.Parse(mData.ServerIp), mData.Port);

            mClient = new System.Net.Sockets.UdpClient();
            mClient.Connect(System.Net.IPAddress.Parse(mData.ServerIp), mData.Port);

            mClient.Client.SendTimeout    = mData.DataSendTimeout;
            mClient.Client.ReceiveTimeout = mData.Timeout;

            mIsConnected = true;

            mReceiveThread = new Thread(ThreadPro);
            mReceiveThread.IsBackground = true;
            mReceiveThread.Start();

            return(base.InnerOpen());
        }
コード例 #44
0
ファイル: UdpSender.cs プロジェクト: dsedb/UDPSampleForUnity
    IEnumerator send(string server, string message)
    {
        Debug.Log("sending..");
        var u = new System.Net.Sockets.UdpClient();

        u.EnableBroadcast = true;
        u.Connect(server, listenPort);
        var sendBytes = System.Text.Encoding.ASCII.GetBytes(message);

        sent = false;
        u.BeginSend(sendBytes, sendBytes.Length,
                    new System.AsyncCallback(SendCallback), u);
        while (!sent)
        {
            yield return(null);
        }
        u.Close();
        coroutine_ = null;
        Debug.Log("done.");
    }
コード例 #45
0
        private bool SendWOL(List <string> macs)
        {
            string MacAddress = string.Empty;
            bool   result     = false;

            foreach (var item in macs)
            {
                MacAddress = item;
                MacAddress = MacAddress.Replace("-", "");
                MacAddress = MacAddress.Replace(":", "");
                MacAddress = MacAddress.Replace(".", "");
                MacAddress = MacAddress.Replace("_", "");
                MacAddress = MacAddress.Replace(" ", "");
                MacAddress = MacAddress.Replace(",", "");
                MacAddress = MacAddress.Replace(";", "");

                if (MacAddress.Length != 12)
                {
                    //MessageBox.Show("Cant find mac address please supply it menual", "Alert");
                    return(result);
                }

                else
                {
                    //{
                    //    string all = MacAddress;
                    //    StartProcess(Properties.Settings.Default.txt_WOL, all);
                    //    sent = true;
                    //    MessageBox.Show("Wol sent to computer");

                    byte[] mac = new byte[6];

                    /*Fill String in ByteArray*/
                    for (int k = 0; k < 6; k++)
                    {
                        mac[k] = Byte.Parse(MacAddress.Substring(k * 2, 2), System.Globalization.NumberStyles.HexNumber);
                    }

                    // WOL packet is sent over UDP 255.255.255.0:40000.
                    System.Net.Sockets.UdpClient client = new System.Net.Sockets.UdpClient();
                    client.Connect(System.Net.IPAddress.Broadcast, 40000);
                    // WOL packet contains a 6-bytes trailer and 16 times a 6-bytes sequence containing the MAC address.
                    byte[] packet = new byte[17 * 6];
                    // Trailer of 6 times 0xFF.
                    for (int i = 0; i < 6; i++)
                    {
                        packet[i] = 0xFF;
                    }
                    // Body of magic packet contains 16 times the MAC address.
                    for (int i = 1; i <= 16; i++)
                    {
                        for (int j = 0; j < 6; j++)
                        {
                            packet[i * 6 + j] = mac[j];
                        }
                    }
                    client.Send(packet, packet.Length);
                    // return true;
                    //MessageBox.Show("הדלקת מחשב מרוחק הסתיימה", "הודעה");
                    result = true;
                }
            }
            return(result);


            //catch
            //{
            //    MessageBox.Show("לא הצלחתי להדליק מחשב מרוחק", "שגיאה");
            //}
        }
コード例 #46
0
ファイル: UdpClient.cs プロジェクト: Thorarin/Edison
 public Task ConnectAsync(string remoteHost, int remotePort)
 {
     _client.Connect(remoteHost, remotePort);
     return(Task.FromResult(true));
 }
コード例 #47
0
        // send thread
        private void SendData()
        {
            System.Net.Sockets.UdpClient cliente = new System.Net.Sockets.UdpClient();



            while (!conectado)
            {
                ;
            }
            cliente.Connect(anyIP.Address, puerto);
            byte[] timeToVibrate = new byte[3];
            timeToVibrate[0] = 5;
            timeToVibrate[1] = (byte)(vibrationTime & 0x000000FF);
            timeToVibrate[2] = (byte)((vibrationTime >> 4) & 0x000000FF);
            cliente.Send(timeToVibrate, timeToVibrate.Length);

            //miramos latencia con un ping
            Ping      pingSender = new Ping();
            PingReply reply      = pingSender.Send(anyIP.Address);

            if (reply.Status == IPStatus.Success)
            {
                trackerInfo.AddLatencyOfNetwork((int)(reply.RoundtripTime / 2));
            }
            pingSender.Dispose();


            while (sending)
            {
                if (vibrate)
                {
                    byte[] vibrateMessage = new byte[1];
                    vibrateMessage[0] = 2;
                    vibrate           = false;
                    cliente.Send(vibrateMessage, vibrateMessage.Length);
                }
                if (send)
                {
                    send = false;
                    cliente.Send(byteImg, byteImg.Length); //este mensaje tiene de latencia 5ms aprox cuando hace ping
                }
                if (sendVibrationAgain)
                {
                    sendVibrationAgain = false;
                    timeToVibrate[0]   = 5;
                    timeToVibrate[1]   = (byte)(vibrationTime & 0x000000FF);
                    timeToVibrate[2]   = (byte)((vibrationTime >> 4) & 0x000000FF);
                    cliente.Send(timeToVibrate, timeToVibrate.Length);
                }
                if (keepAlive)
                {
                    byte[] keepAliveByte = new byte[1];
                    keepAliveByte[0] = 6;
                    keepAlive        = false;
                    alive            = false;
                    cliente.Send(keepAliveByte, keepAliveByte.Length);
                }
            }
            byte[] sendData = new byte[1];
            //fin de comunicación
            sendData[0] = 1;
            cliente.Send(sendData, sendData.Length);
        }
コード例 #48
0
        public static SteamGameServer GetServerInfo(IPEndPoint gameServerQueryEndpoint)
        {
            byte[] startBytes  = new byte[] { 0xFF, 0xFF, 0xFF, 0xFF };
            byte   Header      = 0x54;
            string qryAsString = "Source Engine Query";

            List <byte> qry = new List <byte>();

            qry.AddRange(startBytes);
            qry.Add(Header);
            qry.AddRange(Encoding.Default.GetBytes(qryAsString));
            qry.Add(0x00);

            ServerQueryResponse item = null;
            var sw     = new System.Diagnostics.Stopwatch();
            var buffer = new byte[2048];

            using (System.Net.Sockets.UdpClient udp = new System.Net.Sockets.UdpClient())
            {
                try
                {
                    udp.Connect(gameServerQueryEndpoint);

                    udp.AllowNatTraversal(true);
                    udp.Client.ReceiveTimeout = 300;

                    sw.Start();
                    udp.Send(qry.ToArray(), qry.Count);

                    System.Net.Sockets.SocketError errorCode;
                    var receivedLenght = udp.Client.Receive(buffer, 0, 2048, System.Net.Sockets.SocketFlags.None,
                                                            out errorCode);
                    sw.Stop();
                    if (errorCode != System.Net.Sockets.SocketError.Success)
                    {
                        return(null);
                    }
                    if (receivedLenght == buffer.Length)
                    {
                        throw new Exception("Buffer zu klein");
                    }


                    var receivedBytes = new byte[receivedLenght];
                    Buffer.BlockCopy(buffer, 0, receivedBytes, 0, receivedLenght);
                    //var receivedBytes = udp.Receive(ref endp);

                    var enconding = System.Text.Encoding.UTF8; // System.Text.Encoding.ASCII;

                    using (var mem = new System.IO.MemoryStream(receivedBytes))
                        using (var br = new System.IO.BinaryReader(mem, CharEncoding))
                        {
                            br.ReadInt32();
                            br.ReadByte();

                            item                 = new ServerQueryResponse();
                            item.IpAdresse       = gameServerQueryEndpoint.Address.ToString();
                            item.ProtocolVersion = br.ReadByte();

                            item.Ping = (int)sw.ElapsedMilliseconds;

                            var count = Array.FindIndex(receivedBytes, (int)mem.Position, IsNULL) - (int)mem.Position;
                            item.GameServerName = enconding.GetString(br.ReadBytes(count));
                            br.ReadByte(); // null-byte

                            count    = Array.FindIndex(receivedBytes, (int)mem.Position, IsNULL) - (int)mem.Position;
                            item.Map = enconding.GetString(br.ReadBytes(count));
                            br.ReadByte(); // null-byte
                            //item.Map = ReadStringNullTerminated(br, enconding);

                            count       = Array.FindIndex(receivedBytes, (int)mem.Position, IsNULL) - (int)mem.Position;
                            item.Folder = enconding.GetString(br.ReadBytes(count));
                            br.ReadByte(); // null-byte

                            count     = Array.FindIndex(receivedBytes, (int)mem.Position, IsNULL) - (int)mem.Position;
                            item.Game = enconding.GetString(br.ReadBytes(count));
                            br.ReadByte(); // null-byte

                            item.ID = br.ReadInt16();

                            item.CurrentPlayerCount = br.ReadByte();

                            item.MaxPlayerCount = br.ReadByte();

                            item.CurrentBotsCount = br.ReadByte();

                            item.ServerType = (ServerQueryRequestType)br.ReadByte();

                            item.Password = br.ReadByte() == 1;

                            item.VAC = br.ReadByte() == 1;

                            item.Mode = br.ReadByte() == 1;

                            count        = Array.FindIndex(receivedBytes, (int)mem.Position, IsNULL) - (int)mem.Position;
                            item.Version = enconding.GetString(br.ReadBytes(count));
                            br.ReadByte(); // null-byte

                            var edfCode = br.ReadByte();

                            item.Data = receivedBytes;

                            if ((edfCode & 0x80) == 0x80)
                            {
                                item.GamePort = br.ReadUInt16();
                            }



                            if ((edfCode & 0x10) == 0x10)
                            {
                                item.ServerSteamId = br.ReadInt64();
                            }

                            //if ((edfCode & 0x40) == 0x40)
                            //    Console.WriteLine("spectator server");

                            if ((edfCode & 0x20) == 0x20)
                            {
                                count         = Array.FindIndex(receivedBytes, (int)mem.Position, IsNULL) - (int)mem.Position;
                                item.Keywords = enconding.GetString(br.ReadBytes(count));
                                br.ReadByte(); // null-byte
                            }

                            if ((edfCode & 0x01) == 0x01)
                            {
                                item.GameID = br.ReadInt64();
                            }

                            // https://community.bistudio.com/wiki/STEAMWORKSquery
                            // https://developer.valvesoftware.com/wiki/Master_Server_Query_Protocol
                        }

                    RequestRules(item, udp);

                    if (item.CurrentPlayerCount > 0)
                    {
                        udp.Client.ReceiveTimeout = Math.Max(300, Convert.ToInt32((6d * item.CurrentPlayerCount)));
                        RequestPlayers(item, udp);
                    }
                }
                catch
                {
                    sw.Stop();
                }
            }
            return(item != null
                ? new SteamGameServer
            {
                Host = gameServerQueryEndpoint.Address,
                QueryPort = gameServerQueryEndpoint.Port,
                Name = item.GameServerName,
                //Gamename = SteamGameNameFilter,
                Map = item.Map,
                Mission = item.Game,
                MaxPlayers = item.MaxPlayerCount,
                CurrentPlayerCount = item.CurrentPlayerCount,
                Passworded = item.Password,
                Port = item.GamePort,
                Version = item.Version,
                Keywords = item.Keywords,
                CurrentPlayers = new string[0],
                Ping = item.Ping,
                Players = item.Players?.Cast <ISteamGameServerPlayer>().ToArray(),
                Mods = GetValue("modNames", item.KeyValues),
                Modhashs = GetValue("modHashes", item.KeyValues),
                Signatures = GetValue("sigNames", item.KeyValues),
                VerifySignatures = item.Keywords.Contains(",vt,")
            }
                : null);
        }
コード例 #49
0
        public static SteamGameServerQueryEndPoint[] GetServerList(string gamename,
                                                                   Action <SteamGameServerQueryEndPoint> itemGenerated)
        {
            // https://developer.valvesoftware.com/wiki/Master_Server_Query_Protocol

            var queryEndPoints = new List <SteamGameServerQueryEndPoint>(5000);

            var addressBytes = new byte[4];
            var portBytes    = new byte[2];


            var dnsEntry = System.Net.Dns.GetHostEntry("hl2master.steampowered.com");

            //var ip = dnsEntry.AddressList.Length > 1 ? dnsEntry.AddressList[1] : dnsEntry.AddressList[0];
            foreach (var ip in dnsEntry.AddressList)
            {
                Debug.WriteLine($"Read from  {ip}");
                var        roundtrips   = 0;
                IPEndPoint lastEndPoint = new IPEndPoint(0, 0);
                queryEndPoints.Clear();

                using (System.Net.Sockets.UdpClient udp = new System.Net.Sockets.UdpClient())
                {
                    queryEndPoints.Clear();
                    var hasErros = false;

                    //udp.Connect("208.64.200.52", 27011);
                    while (true)
                    {
                        byte[] buffer = null;
                        try
                        {
                            udp.Connect(ip, 27011);
                            string request = "1ÿ";
                            request += lastEndPoint + "\0";
                            request += "\\gamedir\\" + gamename;
                            //request += "\\empty\\0";

#if DEBUG //request += @"\name_match\*EUTW*";
#endif

                            request += "\0";

                            var bytes = CharEncoding.GetBytes(request);

                            //udp.Connect("146.66.155.8", 27019);
                            IPEndPoint endp = udp.Client.RemoteEndPoint as IPEndPoint;
                            udp.Client.ReceiveTimeout = 900;

                            var sendlen = udp.Send(bytes, bytes.Length);
#if DEBUG
                            if (sendlen != bytes.Length)
                            {
                                Trace.WriteLine("IServerRepository.GetServerList - sendlen != bytes.Length");
                            }
#endif

                            roundtrips++;
                            buffer = udp.Receive(ref endp);
                        }
                        catch (System.Net.Sockets.SocketException)
                        {
                            //hasErros = true;
                            break;
                        }
                        catch (TimeoutException)
                        {
                            hasErros = true;
                            break;
                        }
                        catch (ObjectDisposedException)
                        {
                            hasErros = true;
                            break;
                        }

                        using (var mem = new System.IO.MemoryStream(buffer, false))
                            using (var br = new System.IO.BinaryReader(mem, Encoding.UTF8))
                            {
                                var i = br.ReadUInt32();
                                i = br.ReadUInt16();

                                while (mem.Position < mem.Length)
                                {
                                    addressBytes[0] = br.ReadByte();
                                    addressBytes[1] = br.ReadByte();
                                    addressBytes[2] = br.ReadByte();
                                    addressBytes[3] = br.ReadByte();

                                    portBytes[0] = br.ReadByte();
                                    portBytes[1] = br.ReadByte();

                                    int port = portBytes[0] << 8 | portBytes[1];


                                    if (addressBytes.All(b => b == 0))
                                    {
                                        break;
                                    }

                                    lastEndPoint = new IPEndPoint(new IPAddress(addressBytes), port);

                                    var item = new SteamGameServerQueryEndPoint();
                                    item.Host      = lastEndPoint.Address;
                                    item.QueryPort = lastEndPoint.Port;
                                    queryEndPoints.Add(item);
                                    if (itemGenerated != null)
                                    {
                                        itemGenerated(item);
                                    }
                                }

                                Debug.WriteLine("RoundTrips {0} - {1}", roundtrips, lastEndPoint.ToString());

                                if (addressBytes.All(b => b == 0))
                                {
                                    break;
                                }
                            }
                    }
                    if (!hasErros)
                    {
                        break;
                    }
                }
            }

            return(queryEndPoints.Distinct(new SteamGameServerQueryEndPointComparer()).ToArray());
        }
コード例 #50
-1
ファイル: MasterServer.cs プロジェクト: griha41/Steam.Query
        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;
        }