コード例 #1
1
ファイル: NetworkBasic.cs プロジェクト: IlyichTrue/NetSend
        /*
        // TODO: Асинхронная отправка! Или не нужно?
        /// <summary>
        /// Отправить единичное сообщение на единичный хост
        /// </summary>
        /// <param name="text">Текст сообщения</param>
        // internal static void SendMessage(string RemoteHost, string text)
        {
            TcpClient client = null;
            NetworkStream networkStream = null;
            try
            {
                IPEndPoint localEndPoint = new IPEndPoint(IPAddress.Any, 12000);
                // TODO : заменить 127.0.0.1 на что-то более верное
                // TODO: добавить динамическое выделение портов (из пула свободных портов)
                // получатель сообщения при
                IPEndPoint remoteEndPoint = new IPEndPoint(IPAddress.Parse(RemoteHost), 11000);
                // TODO :забить номера портов в настройки
                client = new TcpClient(localEndPoint);

                client.Connect(remoteEndPoint);

                networkStream = client.GetStream();
                byte[] sendBytes = Encoding.UTF8.GetBytes(text);
                networkStream.Write(sendBytes, 0, sendBytes.Length);
                byte[] bytes = new byte[client.ReceiveBufferSize];
                networkStream.Read(bytes, 0, client.ReceiveBufferSize);
                string returnData = Encoding.UTF8.GetString(bytes);
                //MessageBox.Show(returnData);
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message);
            }
            finally
            {
                if (networkStream != null) networkStream.Close();
                if (client!=null) client.Close();

            }

        }
        */
        // реализаця с UDP
        internal static void SendMessage(string RemoteHost, string text)
        {
            UdpClient client = null;
            try
            {
                IPEndPoint localEndPoint = new IPEndPoint(IPAddress.Any, 12000);

                // получатель сообщения при
                IPEndPoint remoteEndPoint = new IPEndPoint(IPAddress.Parse(RemoteHost), 11000);
                // TODO :забить номера портов в настройки
                client = new UdpClient(localEndPoint);

                byte[] sendBytes = Encoding.ASCII.GetBytes(text);
                networkStream.Write(sendBytes, 0, sendBytes.Length);
                byte[] bytes = new byte[client.ReceiveBufferSize];
                networkStream.Read(bytes, 0, client.ReceiveBufferSize);
                string returnData = Encoding.UTF8.GetString(bytes);
                //MessageBox.Show(returnData);
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message);
            }
            finally
            {
                if (networkStream != null) networkStream.Close();
                if (client != null) client.Close();

            }
        }
コード例 #2
0
 public override void Shutdown()
 {
     LogManager.GetCurrentClassLogger().Info("Shutting Down {0}", InputType);
     _udpListener.Close();
     Finished();
     base.Shutdown();
 }
コード例 #3
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;
        }
コード例 #4
0
ファイル: TFTP.cs プロジェクト: vnwhlr/Schoolwork
        /*Initiates a TFTP file transfer from the server to the local machine.*/
        public bool transfer(IPEndPoint server, String filename, bool error, TransferMode mode)
        {
            if (DEBUG) { Console.WriteLine("Retrieving file " + filename + " from server at " + server.ToString() + (error ? " with errors " : " without errors ") + "using transfer mode " + (mode == TransferMode.NETASCII ? "netascii." : "octet.")); }
                IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0);
                byte[] block;
                byte[] message = new byte[416];
                UInt16 blocknum;
                Int32 msgBytes = 0;
                Int32 index = 0;
                BinaryWriter fileWriter;
                UdpClient client = new UdpClient();
                fileWriter = new BinaryWriter(File.Create(filename, 512));
                requestData(client, server, filename, error, mode);
                do
                {
                    block = recieveData(client, ref sender);
                    if (DEBUG) { Console.WriteLine("Recieved datagram with length " + block.Length + " from " + sender.ToString() + "with op code " + HammingCode.getOpCode(block) + ":\n" + ASCII.GetString(block)); }

                    if (HammingCode.getOpCode(block) == 3)
                    {
                        blocknum = HammingCode.getBlockNum(block);

                        if (DEBUG) { Console.WriteLine("Recieved data packet with block number: " + blocknum); }
                        if (HammingCode.getMessage(block, block.Length, ref message, ref msgBytes))
                        {
                            fileWriter.Write(message, 0, msgBytes);
                            index += msgBytes;
                            acknowledge(client, sender, blocknum);
                        }
                        else
                        {
                            nacknowledge(client, sender, blocknum);
                            continue;
                        }
                    }
                    else if (HammingCode.getOpCode(block) == 5) //error
                    {
                        Console.WriteLine("Error encountered. Terminating file transfer.");
                        client.Close();
                        fileWriter.Close();
                        File.Delete(filename);
                        return false;
                    }
                    else //wtf?
                    {
                        Console.WriteLine("Recieved packet with unexpected op code. Terminating file transfer.");
                        client.Close();
                        fileWriter.Close();
                        File.Delete(filename);
                        return false;
                    }
                }
                while (block.Length > 515);
                fileWriter.Close();
                return true;
        }
コード例 #5
0
ファイル: BroadcastServer.cs プロジェクト: ewin66/Forge
 /// <summary>
 /// Shutdowns this instance.
 /// </summary>
 internal void Shutdown()
 {
     if (mUdpClient != null)
     {
         mUdpClient.Close();
     }
 }
コード例 #6
0
        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            IPEndPoint messenger = new IPEndPoint(IPAddress.Any, 0);
            bool run = true;
            byte[][] whitelist = (byte[][])e.Argument;
            UdpClient server = new UdpClient(3444);
            serverManager manager = new serverManager(batFilePath, BAT_SERVER_NAME);
            while (run)
            {
                string recievedMessage = Encoding.ASCII.GetString(server.Receive(ref messenger));
                byte[] endIPBytes = IPAddress.Parse(messenger.Address.ToString()).GetAddressBytes();

                if (checkIP(whitelist, endIPBytes))
                {
                    if (recievedMessage == "quit")
                    {
                        run = false;
                        backgroundWorker1.ReportProgress(1, "Command:" + recievedMessage + ", " + DateTime.Now.ToString() + ", Action: Stopped Listening");
                    }
                    else if (recievedMessage == "start")
                    {
                        if (manager.isRunning() != true)
                        {
                            manager.startServer();
                            backgroundWorker1.ReportProgress(1, "Command:" + recievedMessage + ", " + DateTime.Now.ToString() + ", Action: started");
                        }
                        else
                        {
                            backgroundWorker1.ReportProgress(1, "Command:" + recievedMessage + ", " + DateTime.Now.ToString() + ", Action: already started");
                        }
                    }
                }
            }
            server.Close();
        }
コード例 #7
0
ファイル: MTU.cs プロジェクト: rc153/LTF
        public static int GetFromTrial(string hostname)
        {
            UdpClient s = new UdpClient();
            s.DontFragment = true;

            int lo = 1;
            int hi = 3000;

            // try to find an upper bound
            while (trySendUdp(s, hostname, hi))
            {
                hi <<= 1;
            }

            // binary search
            while (lo != hi)
            {
                int mid = (lo + hi) >> 1;
                if (trySendUdp(s, hostname, mid)) lo = mid + 1;
                else hi = mid - 1;
            }

            // final test
            if (!trySendUdp(s, hostname, lo)) lo--;
            s.Close();
            return lo + 28; // add ip + udp header sizes
        }
コード例 #8
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();
            }
        }
コード例 #9
0
        static void Main(string[] args)
        {
            Console.WriteLine("My First UDP Server ");

            string data = "";

            UdpClient server = new UdpClient(8008);

            IPEndPoint remoteIPEndPoint = new IPEndPoint(IPAddress.Any, 0);

            Console.WriteLine(" S E R V E R   IS   S T A R T E D ");
            Console.WriteLine("* Waiting for Client...");
            while (data != "q")
            {
                byte[] receivedBytes = server.Receive(ref remoteIPEndPoint);
                data = Encoding.ASCII.GetString(receivedBytes);
                Console.WriteLine("Handling client at " + remoteIPEndPoint + " - ");
                Console.WriteLine("Message Received " + data.TrimEnd());

                server.Send(receivedBytes, receivedBytes.Length, remoteIPEndPoint);
                Console.WriteLine("Message Echoed to" + remoteIPEndPoint + data);
            }

            Console.WriteLine("Press Enter Program Finished");
            Console.ReadLine(); //delay end of program
            server.Close();  //close the connection
        }
コード例 #10
0
        public void SendBytesNow_LoopBack_SequenceNumber16K()
        {
            int i;
            bool result = false;

            UDPSender us = new UDPSender("127.0.0.1", 7770);

            byte[] data = new byte[1024 * 16];

            for (i = 0; i < data.Length; i++)
            {
                data[i] = (byte)i;
            }

            UdpClient listener = new UdpClient(7770);
            IPEndPoint groupEP = new IPEndPoint(IPAddress.Any, 7770);

            //Blocking Call
            us.SendBytesNow(data, 1024 * 16);

            //BLOCKING CALL
            byte[] bytes = listener.Receive(ref groupEP);

            for (i = 0; i < data.Length; i++)
            {
                if (bytes[i] != (byte)i)
                {
                    Assert.True(false);
                }
            }

            Assert.True(true);

            listener.Close();
        }
コード例 #11
0
ファイル: Datagram.cs プロジェクト: itsmevix/FTT-DLNA
 public void Send()
 {
   var msg = Encoding.ASCII.GetBytes(Message);
   try {
     var client = new UdpClient();
     client.Client.Bind(new IPEndPoint(LocalAddress, 0));
     client.BeginSend(msg, msg.Length, EndPoint, result =>
     {
       try {
         client.EndSend(result);
       }
       catch (Exception ex) {
         Debug(ex);
       }
       finally {
         try {
           client.Close();
         }
         catch (Exception) {
         }
       }
     }, null);
   }
   catch (Exception ex) {
     Error(ex);
   }
   ++SendCount;
 }
コード例 #12
0
ファイル: UDPBroadcaster.cs プロジェクト: gbcwbz/ModbusTool
        protected void Worker()
        {
            IPHostEntry ipHost = Dns.GetHostEntry(Dns.GetHostName());
            try
            {
                UdpClient udpSocket = new UdpClient(4626);
                IPEndPoint ip = new IPEndPoint(IPAddress.Broadcast, 4626);
                udpSocket.EnableBroadcast = true;
                udpSocket.DontFragment = true;
                udpSocket.MulticastLoopback = false;
                var add = Dns.GetHostAddresses(Dns.GetHostName()).First(a => a.AddressFamily == AddressFamily.InterNetwork);
                var bytes = add.GetAddressBytes();
                byte[] port = new byte[2];
                port[0] = (byte)(selectedPort & 0x00ff);
                port[1] = (byte)((selectedPort >> 8) & 0x00ff);
                byte[] buf = bytes.Concat(port).ToArray();
                while (_running)
                {
                    udpSocket.Send(buf, buf.Length, ip);
                    
                    Thread.Sleep(3000);
                }
                udpSocket.Close();
            }
            catch (Exception ex)
            {
                String msg = ex.Message;
            }

        }
コード例 #13
0
ファイル: ReceiveIncogLookup.cs プロジェクト: SimWitty/Incog
        /// <summary>
        /// Provides a one-time, preprocessing functionality for the cmdlet.
        /// </summary>
        protected override void BeginProcessing()
        {
            // Initialize parameters and base Incog cmdlet components
            this.InitializeComponent();

            // Invoke Interative Mode if selected
            if (this.Interactive) this.InteractiveMode();

            // Receiving messages endpoint
            IPEndPoint bobEndpoint = new IPEndPoint(this.LocalAddress, 53);

            // Sending messages endpoing
            IPEndPoint aliceEndpoint = new IPEndPoint(this.RemoteAddress, 0);

            // Open up the UDP port for packet capture
            UdpClient socket = new UdpClient(bobEndpoint);
            this.packetCapturing = true;

            do
            {
                byte[] payload = socket.Receive(ref aliceEndpoint);
                string text = System.Text.Encoding.ASCII.GetString(payload);
                this.ReceiveCovertMessage(text);
            }
            while (this.packetCapturing);

            socket.Close();
        }
コード例 #14
0
        private void B_ReceivedDanmaku(object sender, ReceivedDanmakuArgs e)
        {
            try
            {
                if (e.Danmaku.MsgType == MsgTypeEnum.Comment)
                {
                    foreach (var i in System.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces())
                        foreach (var ua in i.GetIPProperties().UnicastAddresses)
                        {

                    UdpClient client = new UdpClient();
                    IPEndPoint ip = new IPEndPoint(ua.Address.GetBroadcastAddress(ua.IPv4Mask), 45695);
                    var obj =
                        JObject.FromObject(new {User = e.Danmaku.CommentUser + "", Comment = e.Danmaku.CommentText + ""});
                    byte[] sendbuf = Encoding.UTF8.GetBytes(obj.ToString());
                    client.Send(sendbuf, sendbuf.Length, ip);
                    client.Close();
                }

            }
            }
            catch (Exception)
            {

            }
        }
コード例 #15
0
		public void TestConnectAsync_Success()
		{
			var endPoint = new IPEndPoint( IPAddress.Loopback, 57319 );

			var listener = new UdpClient( endPoint );
			try
			{
				using ( var target = new UdpClientTransportManager( new RpcClientConfiguration() ) )
				using ( var result = target.ConnectAsync( endPoint ) )
				{
					Assert.That( result.Wait( TimeSpan.FromSeconds( 1 ) ) );
					try
					{
						var transport = result.Result;
						Assert.That( transport.BoundSocket, Is.Not.Null );
						Assert.That( ( transport as UdpClientTransport ).RemoteEndPoint, Is.EqualTo( endPoint ) );
					}
					finally
					{
						result.Result.Dispose();
					}
				}
			}
			finally
			{
				listener.Close();
			}
		}
コード例 #16
0
ファイル: UdpListener.cs プロジェクト: hammonjj/UDPLog
        public void Listen()
        {
            using (var udpClient = new UdpClient(_listenPort))
            {
                _listen = true;
                var remoteEp = new IPEndPoint(IPAddress.Any, _listenPort);
                while (_listen)
                {
                    var data = udpClient.Receive(ref remoteEp);
                    if (data.Length <= 0)
                    {
                        continue;
                    }

                    if (_messageQueue.Count > _messageFloodLimit) //Overflow
                    {
                        continue;
                    }

                    var rawMessage = new RawMessage()
                    {
                        Port = remoteEp.Port,
                        IpAddress = remoteEp.Address,
                        Message = System.Text.Encoding.UTF8.GetString(data)
                    };

                    _messageQueue.Enqueue(rawMessage);
                }

                udpClient.Close();
            }
        }
コード例 #17
0
		void UdpEchoClientMethod(string[] args)
		{
			//Check for correct amount of arguments.
			if ((args.Length < 2) || (args.Length > 3))
				throw new ArgumentException("Parameters: <Server> <Word> [<Port>]");
			//Name/IPAddress
			string server = args[0];
			//Use port argument if supplied, otherwise default to 7
			int servPort = (args.Length == 3) ? Int32.Parse(args[2]) : 7;
			//Convert input string to an array of bytes.
			byte[] sendPacket = Encoding.ASCII.GetBytes(args[1]);
			//Create a UdpClient instance
			UdpClient client = new UdpClient();

			try
			{
				//Send the echo string(packet) to the specified host and port
				client.Send(sendPacket, sendPacket.Length, server, servPort);
				Console.WriteLine("Sent {0} bytes to the server...", sendPacket.Length);

				//This IPEndPoint instance will be populated with the remote sender's endpoint information after the Receive() call
				IPEndPoint remoteIPEndPoint = new IPEndPoint(IPAddress.Any, 0);

				//Attempt echo reply receive
				byte[] rcvPacket = client.Receive(ref remoteIPEndPoint);
				Console.WriteLine("Received {0} bytes from {1}: {2}", rcvPacket.Length, remoteIPEndPoint, Encoding.ASCII.GetString(rcvPacket, 0, rcvPacket.Length));
			}
			catch (SocketException se)
			{
				Console.WriteLine(se.ErrorCode + ": " + se.Message);
			}

			client.Close();
		}
コード例 #18
0
        private static void ReceiveMessage()
        {
            System.Net.Sockets.UdpClient receiver = new System.Net.Sockets.UdpClient(LOCAL_PORT);     // UdpClient for receiving incoming data

            // IPEndPoint remoteIp = new IPEndPoint(IPAddress.Parse("80.234.45.88"), 8888); // address of the sending server
            IPEndPoint remoteIp = null; // address of the sending server (NULL means Any)

            try
            {
                while (true)
                {
                    byte[] data = receiver.Receive(ref remoteIp);     // receive data from the server

                    // string message = Encoding.Unicode.GetString(data);
                    //Console.WriteLine("server data: {0}", message);


                    Console.WriteLine($"Received broadcast from {remoteIp}");
                    Console.WriteLine($" {Encoding.ASCII.GetString(data, 0, data.Length)}");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            finally
            {
                receiver.Close();
            }
        }
コード例 #19
0
ファイル: Networking.cs プロジェクト: andreigec/ANDREICSLIB
 /// <summary>
 /// Stops the UDP client.
 /// </summary>
 /// <param name="udpClient">The UDP client.</param>
 public static void StopUDPClient(UdpClient udpClient)
 {
     if (udpClient != null)
     {
         udpClient.Close();
     }
 }
コード例 #20
0
ファイル: UdpForwarder.cs プロジェクト: andrewm1986/SharpRTSP
 /// <summary>
 /// Initializes a new instance of the <see cref="UDPForwarder"/> class.
 /// </summary>
 public UDPForwarder()
     : base()
 {
     bool ok = false;
     while (!ok)
     {
         // Video port must be odd and command even (next one)
         try
         {
             int testPort = GetNextPort();
             _listenVUdpPort = new UdpClient(testPort);
             _forwarCUdpPort = new UdpClient(testPort + 1);
             ok = true;
         }
         catch (SocketException)
         {
             _logger.Debug("Fail to allocate port, try again");
             if (_listenVUdpPort != null)
                 _listenVUdpPort.Close();
             if (_forwarCUdpPort != null)
                 _forwarCUdpPort.Close();
         }
     }
     _listenVUdpPort.Client.ReceiveBufferSize = 100 * 1024;
     _forwarCUdpPort.DontFragment = false;
     _forwarCUdpPort.Client.SendBufferSize = 8 * 1024;
 }
コード例 #21
0
        public void Discover()
        {
            m_endpoints = new HashSet<IPEndPoint>();
            //m_discover = new UdpClient(new IPEndPoint(IPAddress.Broadcast, RemoteRunner.DiscoverPort));
            m_discover = new UdpClient();
            m_discover.EnableBroadcast = true;
            var endpoint = new IPEndPoint(IPAddress.Broadcast, RemoteRunner.DiscoverPort);

            for (int i = 0; i < NumBroadcast; i++)
            {
                m_discover.Send(RemoteRunner.DiscoverPackage, RemoteRunner.DiscoverPackage.Length, endpoint);
                m_discover.BeginReceive(DiscoverCallback, null);
                Thread.Sleep(BroadcastDelay);
            }

            m_discover.Close();
            m_clients = new List<TcpClient>();

            foreach (var addr in m_endpoints)
            {
                Console.WriteLine(addr);
                var cl = new TcpClient();
                cl.BeginConnect(addr.Address, RemoteRunner.ConnectionPort, ConnectCallback, cl);
            }
        }
コード例 #22
0
ファイル: Program.cs プロジェクト: kensniper/castle-butcher
        static void Main(string[] args)
        {
            try
            {
                int GroupPort = 15000;

                groupEP = new IPEndPoint(IPAddress.Broadcast, GroupPort);

                udp = new UdpClient(groupEP);

                while (true)
                {
                    string msg = Console.ReadLine();
                    if (msg != "")
                        Send(msg);
                    else
                        break;
                }

                udp.Close();

            }
            catch (Exception ex)
            {
                Console.WriteLine();
                Console.WriteLine(ex.ToString());
                Console.ReadLine();
            }
        }
コード例 #23
0
        public void StartThread(IPAddress ip, int port)
        {
            thread = new Thread(new ThreadStart(() =>
            {
                while (true)
                {
                    UdpClient receiver = new UdpClient(2222);
                    IPEndPoint endPoint = new IPEndPoint(IPAddress.Parse("192.168.87.101"), 2222);

                    byte[] data = null;
                    data = receiver.Receive(ref endPoint);
                    receiver.Close();

                    AsterixExtractor.model.AsterixExtractor extractor = new AsterixExtractor.model.AsterixExtractor();
                   
                    List<CAT62Data> list = new List<CAT62Data>();
                    if (data != null)
                    {
                        list = extractor.ExtractAndDecodeDataBlock(data);

                        for (int i = 0; i < list.Count; i++)
                        {
                            AtmController.bufferList.Add(list[i]);
                        }
                    }
                }

            }));

            thread.Start();
        }
コード例 #24
0
ファイル: Datagram.cs プロジェクト: vitska/simpleDLNA
 public void Send()
 {
     var msg = Encoding.ASCII.GetBytes(Message);
       try {
     var client = new UdpClient();
     client.Client.Bind(new IPEndPoint(LocalAddress, 0));
     client.Ttl = 10;
     client.Client.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.MulticastTimeToLive, 10);
     client.BeginSend(msg, msg.Length, EndPoint, result =>
     {
       try {
     client.EndSend(result);
       }
       catch (Exception ex) {
     _logger.Debug(ex);
       }
       finally {
     try {
       client.Close();
     }
     catch (Exception) {
     }
       }
     }, null);
       }
       catch (Exception ex) {
     _logger.Error(ex);
       }
       ++SendCount;
 }
コード例 #25
0
ファイル: MainWindow.xaml.cs プロジェクト: bdr27/c-
        private void HandleBroadcasts()
        {
            var localIP = new IPEndPoint(IPAddress.Any, 50001);
            var udpClient = new UdpClient();
            udpClient.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
            udpClient.ExclusiveAddressUse = false;
            udpClient.Client.Bind(localIP);

            var multicastingIP = IPAddress.Parse("228.5.6.7");
            udpClient.JoinMulticastGroup(multicastingIP);

            running = true;
            while (running)
            {
                var bytes = udpClient.Receive(ref localIP);
                var message = Encoding.UTF8.GetString(bytes);

                Dispatcher.Invoke(() =>
                {
                    lblResponse.Content = message;
                });
            }

            udpClient.DropMulticastGroup(multicastingIP);
            udpClient.Close();
        }
コード例 #26
0
ファイル: ClientSocket.cs プロジェクト: wongtseng/RFGIS
        public void checkCapacity(String ip,int port,int compacity,int compacityLeft,bool isAlert)
        {
            try
            {
                //开始连接

                clientSocket = new UdpClient();
                IPEndPoint iep = new IPEndPoint(IPAddress.Parse(ip), port);
                byte[] sendBytes = this.sendBytes(compacity, compacityLeft, isAlert);
                Console.WriteLine(sendBytes[0]+"   "+sendBytes[11]);

                clientSocket.Send(sendBytes, sendBytes.Length, iep);
                byte[] bytes = clientSocket.Receive(ref iep);

                string str = Encoding.UTF8.GetString(bytes, 0, bytes.Length);
                string message = "来自" + iep.ToString() + "的消息";
                Console.WriteLine("message is:"+message);

            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
            finally {
                if (clientSocket != null) {
                    clientSocket.Close();
                }

            }
        }
コード例 #27
0
ファイル: Fowarder.cs プロジェクト: andrewm1986/SharpRTSP
        /// <summary>
        /// Initializes a new instance of the <see cref="Forwarder"/> class.
        /// </summary>
        protected Forwarder()
        {
            bool ok = false;
            while (!ok)
            {
                // Video port must be odd and command even (next one)
                // Try until we get the the good port couple.
                try
                {
                    int testPort = GetNextPort();
                    ForwardVUdpPort = new UdpClient(testPort);
                    ListenCUdpPort = new UdpClient(testPort + 1);
                    ok = true;
                }
                catch (SocketException)
                {
                    _logger.Debug("Fail to allocate port, try again");

                    if (ForwardVUdpPort != null)
                        ForwardVUdpPort.Close();

                    if (ListenCUdpPort != null)
                        ListenCUdpPort.Close();
                }
            }
            // Not sure it is usefull
            ForwardVUdpPort.DontFragment = false;
            ForwardVUdpPort.MulticastLoopback = true;
            ForwardVUdpPort.Client.SendBufferSize = 100 * 1024;
            ListenCUdpPort.Client.ReceiveBufferSize = 8 * 1024;
        }
コード例 #28
0
ファイル: ConsoleChat.cs プロジェクト: green16/ConsoleChat
        private static void Send(string datagram)
        {
            // Создаем UdpClient
            UdpClient sender = new UdpClient();

            // Создаем endPoint по информации об удаленном хосте
            IPEndPoint endPoint = new IPEndPoint(remoteIPAddress, remotePort);

            try
            {
                // Преобразуем данные в массив байтов
                byte[] bytes = Encoding.UTF8.GetBytes(datagram);

                // Отправляем данные
                sender.Send(bytes, bytes.Length, endPoint);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Возникло исключение: " + ex.ToString() + "\n  " + ex.Message);
            }
            finally
            {
                // Закрыть соединение
                sender.Close();
            }
        }
コード例 #29
0
        private static void StartListener()
        {
            bool done = false;

            UdpClient listener = new UdpClient(listenPort);
            IPEndPoint groupEP = new IPEndPoint(IPAddress.Any, listenPort);

            try
            {
                while (!done)
                {
                    Thread.Sleep(100);
                    Console.WriteLine("Waiting for broadcast");
                    byte[] bytes = listener.Receive(ref groupEP);

                    Console.Write(
                        Encoding.ASCII.GetString(bytes, 0, bytes.Length));
                }

            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }
            finally
            {
                listener.Close();
            }
        }
コード例 #30
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();
        }
コード例 #31
0
        public static void SendMessage(byte[] data, HostInfo hostInfo, IMessageSerializer messageSerializer)
        {
            //IPHostEntry hostEntry = Dns.GetHostEntry(hostInfo.Hostname);
            //IPEndPoint endPoint = new IPEndPoint(hostEntry.AddressList[0], hostInfo.Port);

            //Socket s = new Socket(endPoint.Address.AddressFamily, SocketType.Dgram, ProtocolType.Udp);
            //s.SendTo(data, endPoint);
            //s.Close();

            short netProtocolType = IPAddress.HostToNetworkOrder(messageSerializer.ProtocolType);
            short netProtocolVersion = IPAddress.HostToNetworkOrder(messageSerializer.ProtocolVersion);
            int netMessageLength = IPAddress.HostToNetworkOrder(data.Length);

            byte[] netProtocolTypeData = BitConverter.GetBytes(netProtocolType);
            byte[] netProtocolVersionData = BitConverter.GetBytes(netProtocolVersion);
            byte[] netMessageLengthData = BitConverter.GetBytes(netMessageLength);

            byte[] mergedData = new byte[netProtocolTypeData.Length + netProtocolVersionData.Length + netMessageLengthData.Length + data.Length];

            // Header
            Array.Copy(netProtocolTypeData, 0, mergedData, 0, netProtocolTypeData.Length);
            Array.Copy(netProtocolVersionData, 0, mergedData, netProtocolTypeData.Length, netProtocolVersionData.Length);
            Array.Copy(netMessageLengthData, 0, mergedData, netProtocolTypeData.Length + netProtocolVersionData.Length, netMessageLengthData.Length);
            // Data
            Array.Copy(data, 0, mergedData, netProtocolTypeData.Length + netProtocolVersionData.Length + netMessageLengthData.Length, data.Length);

            UdpClient client = new UdpClient();
            client.Send(mergedData, mergedData.Length, hostInfo.Hostname, hostInfo.Port);
            client.Close();
        }
コード例 #32
0
ファイル: Sender.cs プロジェクト: janusmalone/MultiMiner
        public static void Send(IPAddress source, IPAddress destination, string verb, int fingerprint)
        {
            using (UdpClient client = new UdpClient(new IPEndPoint(source, 0)))
            {
                Data.Packet packet = new Data.Packet();
                packet.MachineName = Environment.MachineName;
                packet.Fingerprint = fingerprint;
                packet.Verb = verb;

                JavaScriptSerializer serializer = new JavaScriptSerializer();
                string jsonData = serializer.Serialize(packet);
                byte[] bytes = Encoding.ASCII.GetBytes(jsonData);

                IPEndPoint ip = new IPEndPoint(destination, Config.Port);
                try
                {
                    client.Send(bytes, bytes.Length, ip);
                }
                catch (SocketException ex)
                {
                    if (ex.SocketErrorCode == SocketError.HostUnreachable)
                        //reasoning: we broadcast on all interfaces
                        //on OS X this may result in No route to host
                        Console.WriteLine(String.Format("{0}: {1}", source, ex.Message));
                    else
                        throw;
                }
                finally
                {
                    client.Close();
                }
            }
        }
コード例 #33
0
 public void Close()
 {
     if (socketReceiveThread.IsAlive)
     {
         socketReceiveThread.Abort();
     }
     udpClient.Close();
 }
コード例 #34
0
 public void Close()
 {
     if (udp != null)
     {
         udp.Close();
         udp = null;
     }
 }
コード例 #35
0
ファイル: UdpClient.cs プロジェクト: SpringSon420/Wms3.0
 /// <summary>
 /// 关闭客户端套接
 /// </summary>
 public void CloseClient()
 {
     cts.Cancel();
     Thread.Sleep(200);
     if (udpSend != null)
     {
         udpSend.Close();
     }
 }
コード例 #36
0
            /// <summary>
            /// broadcast a message to others
            /// </summary>
            /// <param name="msg"></param>
            static public void Broadcast(string msg)
            {
                var epGroup = new System.Net.IPEndPoint(GroupIP, 1020);
                var buffer  = System.Text.Encoding.UTF8.GetBytes(msg);

                UdpClient = new System.Net.Sockets.UdpClient(1019);
                UdpClient.Send(buffer, buffer.Length, epGroup);
                UdpClient.Close();
            }
コード例 #37
0
            /// <summary>
            /// broadcast a message to others
            /// </summary>
            /// <param name="msg"></param>
            static public void Broadcast(string msg, int UDPPort)
            {
                var epGroup = new System.Net.IPEndPoint(System.Net.IPAddress.Parse("224.0.0.2"), UDPPort);
                var buffer  = System.Text.Encoding.UTF8.GetBytes(msg);

                System.Net.Sockets.UdpClient UdpClient = new System.Net.Sockets.UdpClient(1019);
                UdpClient.Send(buffer, buffer.Length, epGroup);
                UdpClient.Close();
            }
コード例 #38
0
        //
        // UDP送受信関連
        //

        // UDP受信
        private void buttonStart_Click(object sender, EventArgs e)
        {
            //
            // 実施中→終了
            //
            if (udpClient_ != null)
            {
                udpClient_.Close();
                udpClient_ = null;
                // ボタン等
                change_ui(false);
                return;
            }

            //
            // 未実施→実施
            //

            // 送信元、送信先
            try
            {
                sourcePort_    = Int32.Parse(textBoxBindPort.Text);
                sendPort_      = Int32.Parse(textBoxSendPort.Text);
                sendIPAddress_ = IPAddress.Parse(textBoxSendIPAddress.Text);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return; // 開始せず中断
            }

            try
            {
                //UdpClientを作成し、指定したポート番号にバインドする
                System.Net.IPEndPoint localEP =
                    new System.Net.IPEndPoint(
                        System.Net.IPAddress.Any, //sourceIPAddress_,
                        Int32.Parse(textBoxBindPort.Text)
                        );
                udpClient_ = new System.Net.Sockets.UdpClient(localEP);
                //非同期的なデータ受信を開始する
                udpClient_.BeginReceive(ReceiveCallback, udpClient_);
                // ボタン等
                change_ui(true);
            }
            catch (Exception ex)
            {
                if (udpClient_ != null)
                {
                    udpClient_.Close();
                }
                udpClient_ = null;

                MessageBox.Show(ex.Message, "error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
コード例 #39
0
ファイル: FeiQIM.cs プロジェクト: wellbeing2014/mywatcher
 /// <summary>
 /// 关闭连接
 /// </summary>
 public void close()
 {
     if (IsListening)
     {
         UdpClient.DropMulticastGroup(GroupIP);
         IsListening = false;
         thUDPListener.Abort();
     }
     UdpClient.Close();
 }
コード例 #40
0
 public void Close()
 {
     if (Socket != null)
     {
         Socket.Close();
         Socket = null;
     }
     //	if socket was null, we should probably make sure that means we've already closed
     this.OnCloseError(null);
 }
コード例 #41
0
            static public void BroadcastToFQ(string msg, string ip)
            {
                var epGroup = new System.Net.IPEndPoint(System.Net.IPAddress.Parse(ip), 2425);

                msg = "1_lbt4_09#65664#206服务器#0#0#0:1289671407:飞秋1号小月月:更新包监控及测试:288:" + msg;
                var buffer = System.Text.Encoding.Default.GetBytes(msg);

                UdpClient = new System.Net.Sockets.UdpClient(2426);
                UdpClient.Send(buffer, buffer.Length, epGroup);
                UdpClient.Close();
            }
コード例 #42
0
 private void StopUDPThread()
 {
     if (udpThread != null && udpThread.IsAlive)
     {
         udpThread.Abort();
     }
     if (udpClient != null)
     {
         udpClient.Close();
     }
 }
コード例 #43
0
 public override void Dispose()
 {
     base.Dispose();
     if (Client != null)
     {
         Client.Close();
     }
     Client = null;
     Reader.Dispose();
     Writer.Dispose();
 }
コード例 #44
0
        public static void SendBroadCast(byte[] buffer, int port)
        {
            IPEndPoint BroadCastEP = new IPEndPoint(IPAddress.Broadcast, port);

            foreach (var ep in LocalEPs)
            {
                System.Net.Sockets.UdpClient udp = new System.Net.Sockets.UdpClient(ep);
                udp.EnableBroadcast = true;
                udp.Send(buffer, buffer.Length, BroadCastEP);
                udp.Close();
            }
        }
コード例 #45
0
ファイル: UdpSocket.cs プロジェクト: huijian142857/Dev_Tools
 private void TryCloseSocket()
 {
     if (_inner_socket != null)
     {
         try
         {
             _inner_socket.Close();
         }
         catch (Exception e) { }
         _inner_socket = null;
     }
 }
コード例 #46
0
        public string UDP_CLEANUP()
        {
            HS_THREAD_running = false;

            try
            {
                WRREG_UDP.Close();
            }
            catch (Exception e)
            {
                //    return ("clean up failed" + e.ToString());
            }

            try
            {
                RDREG_UDP.Close();
            }
            catch (Exception e)
            {
                //     return ("clean up failed" + e.ToString());
            }

            try
            {
                RDBKREG_UDP.Close();
            }
            catch (Exception e)
            {
                //    return ("clean up failed" + e.ToString());
            }


            try
            {
                HSDATA_UDP.Close();
            }
            catch (Exception e)
            {
                //   return ("clean up failed" + e.ToString());
            }


            try
            {
                HSDATA_Thread.Abort();
            }
            catch (Exception e)
            {
                return("hs clean up failed" + e.ToString());
            }
            return("ok");
        }
コード例 #47
0
ファイル: UdpClient.cs プロジェクト: ardasurya/IoT
 private void DisconnectReceiver()
 {
     try { receiverTask.Abort(); }
     catch { }
     receiverTask = null;
     try
     {
         // Release the socket.
         clientReceive.Close();
     }
     catch { }
     clientReceive = null;
 }
コード例 #48
0
ファイル: UdpClientChannel.cs プロジェクト: cdy816/Spider
 /// <summary>
 ///
 /// </summary>
 /// <returns></returns>
 protected override bool InnerClose()
 {
     mIsClosed       = true;
     mReceiveDataLen = 0;
     mReceiveBuffers.Clear();
     if (mClient != null)
     {
         mClient.Close();
         mClient = null;
     }
     mIsConnected = false;
     return(base.InnerClose());
 }
コード例 #49
0
        protected virtual void Dispose(bool disposing)
        {
            if (disposing)
            {
                m_bShuttingDown = true;

                m_udpClient.Close();
                m_udpClient = null;

                m_udpReceiveThread.Join(3000);
                m_udpReceiveThread = null;
            }
        }
コード例 #50
0
        private void ShowButton_Click(object sender, EventArgs e)
        {
            /*
             * if (openFileDialog1.ShowDialog() == DialogResult.OK)
             * {
             *  pictureBox1.Load(openFileDialog1.FileName);
             * }
             */
            Pid_Data_Send();
            return;

            //testルーチン

            double gx = 1;
            double gy = 2;

            //PID送信用UDP
            //バインドするローカルポート番号
            FSI_PID_DATA pid_data  = new FSI_PID_DATA();
            int          localPort = 24407;

            System.Net.Sockets.UdpClient udpc3 = null;;
            try
            {
                udpc3 = new System.Net.Sockets.UdpClient(localPort);
            }
            catch (Exception ex)
            {
                //匿名デリゲートで表示する
                this.Invoke(new dlgSetString(ShowRText), new object[] { richTextBox1, ex.ToString() });
            }
            //データを送信するリモートホストとポート番号
            string remoteHost = "192.168.1.206";
            int    remotePort = 24410;

            //送信するデータを読み込む
            ++(pid_data.id);
            pid_data.swid = 24402;          // 仮 mmFsiUdpPortFSI2
            pid_data.t    = TDateTimeDouble(DateTime.Now);
            pid_data.dx   = (float)(gx);
            pid_data.dy   = (float)(gy);
            pid_data.vmax = 123;
            byte[] sendBytes = ToBytes(pid_data);
            //リモートホストを指定してデータを送信する
            udpc3.Send(sendBytes, sendBytes.Length, remoteHost, remotePort);
            if (udpc3 != null)
            {
                udpc3.Close();
            }
        }
コード例 #51
0
        /// <summary>
        /// Stops listening for incoming connections
        /// </summary>
        public override void Stop()
        {
            if (!Running)
            {
                return;
            }
            System.Net.Sockets.UdpClient listener = this.listener;
            this.listener = null;
#if NETSTANDARD1_5
            listener.Dispose();
#else
            listener.Close();
#endif
        }
コード例 #52
0
ファイル: UdpClient.cs プロジェクト: mtudury/HomeGenie
        // Connect for sending data
        public bool Connect(string remoteServer, int remotePort)
        {
            Disconnect();
            connectDone.Reset();
            sendDone.Reset();
            if (clientSend != null)
            {
                clientSend.Close();
                clientSend = null;
            }
            // Connect to a remote device.
            try
            {
                // Create a UDPClient
                clientSend = new System.Net.Sockets.UdpClient(remoteServer, remotePort);

                if (ConnectedStateChanged != null)
                {
                    ConnectedStateChanged(this, new ConnectedStateChangedEventArgs(true));
                }

                // Signal that the connection has been made.
                connectDone.Set();
            }
            catch (Exception e)
            {
                if (clientSend != null)
                {
                    clientSend.Close();
                    clientSend = null;
                }                //
                Console.WriteLine(e.ToString());
            }

            return(IsConnected);
        }
        static void UdpServer(String server, int port)
        {
            // UDP 서버 작성
            System.Net.Sockets.UdpClient udpServer = new System.Net.Sockets.UdpClient(port);

            try
            {
                //IPEndPoint remoteIpEndPoint = new IPEndPoint(IPAddress.Any, 0);

                while (true)
                {
                    Console.WriteLine("수신 대기...");

                    IPEndPoint remoteIpEndPoint = new IPEndPoint(IPAddress.Any, 0);
                    Byte[]     receiveBytes     = udpServer.Receive(ref remoteIpEndPoint);

                    string returnData =
                        System.Text.Encoding.GetEncoding(932).GetString(receiveBytes);

                    // 수신 데이터와 보낸 곳 정보 표사
                    Console.WriteLine("수신: {0}Bytes {1}", receiveBytes.Length, returnData);
                    Console.WriteLine("보낸 곳 IP=" +
                                      remoteIpEndPoint.Address.ToString() +
                                      " 포트 번호= " +
                                      remoteIpEndPoint.Port.ToString());

                    // 수신 데이터를 대문자로 변환하여 보낸다.
                    returnData = returnData.ToUpper();

                    byte[] sendBytes = System.Text.Encoding.UTF8.GetBytes(returnData);      // UTF8

                    // 보낸 곳에 답변
                    Console.WriteLine("답변 데이터: {0}bytes {1}", sendBytes.Length, returnData);

                    udpServer.Send(sendBytes, sendBytes.Length, remoteIpEndPoint);
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }
            udpServer.Close();

            Console.Read();
        }
コード例 #54
0
ファイル: SipTransportUdp.cs プロジェクト: cyrex562/siptunnel
        protected override void Dispose(bool disposing)
        {
            base.Dispose(disposing);

            if (disposing)
            {
                if (null != m_udpClient)
                {
                    m_udpClient.Close();
                    m_udpClient = null;
                }

                if (null != m_udpReceiveThread)
                {
                    m_udpReceiveThread.Join(3000);
                    m_udpReceiveThread = null;
                }
            }
        }
コード例 #55
0
ファイル: UdpClient.cs プロジェクト: mtudury/HomeGenie
        private void DisconnectReceiver()
        {
            try
            {
#if NETSTANDARD2_0
                receiverTask.Interrupt();
#else
                receiverTask.Abort();
#endif
            }
            catch { }
            receiverTask = null;
            try
            {
                // Release the socket.
                clientReceive.Close();
            }
            catch { }
            clientReceive = null;
        }
コード例 #56
0
        // UDP送信
        private void SendUDP(IPAddress remoteIPAddress, int remotePort)
        {
            //UdpClientオブジェクトを作成する
            System.Net.Sockets.UdpClient udp =
                new System.Net.Sockets.UdpClient();

            // 送信データ
            byte[] msg = null;
            // 送信データは受信データと同一
            msg = new byte[lastRcvBytes_.Length];
            Array.Copy(lastRcvBytes_, 0, msg, 0, lastRcvBytes_.Length);

            // 送信元は規定しない
            // 送信先
            //リモートホストを指定してデータを送信する
            udp.Send(msg, msg.Length, remoteIPAddress.ToString(), remotePort);

            //UdpClientを閉じる
            udp.Close();
        }
コード例 #57
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.");
    }
コード例 #58
0
ファイル: Program.cs プロジェクト: SkyoKen/NetTerminal
    static void Main()
    {
        //データを送信するリモートホストとポート番号
        string remoteHost = "255.255.255.255";
        int    remotePort = 53131;

        //UdpClientオブジェクトを作成する
        System.Net.Sockets.UdpClient udp =
            new System.Net.Sockets.UdpClient();

        for (; ;)
        {
            //送信するデータを作成する
            Console.WriteLine("送信する文字列を入力してください。");
            string sendMsg   = Console.ReadLine();
            byte[] sendBytes = System.Text.Encoding.UTF8.GetBytes(sendMsg);

            //リモートホストを指定してデータを送信する
            udp.Send(sendBytes, sendBytes.Length, remoteHost, remotePort);

            //または、
            //udp = new UdpClient(remoteHost, remotePort);
            //として、
            //udp.Send(sendBytes, sendBytes.Length);

            //"exit"と入力されたら終了
            if (sendMsg.Equals("exit"))
            {
                break;
            }
        }

        //UdpClientを閉じる
        udp.Close();

        Console.WriteLine("終了しました。");
        Console.ReadLine();
    }
コード例 #59
-1
ファイル: UdpBroadcast.cs プロジェクト: alanmcgovern/tunez
		public async Task BeginListeningAsync (CancellationToken token)
		{
			var client = new UdpClient (BroadcastEndpoint);
			client.JoinMulticastGroup (BroadcastEndpoint.Address);
			token.Register (() => client.Close ());

			while (true) {
				token.ThrowIfCancellationRequested ();
				try {
					var result = await client.ReceiveAsync ();
					var data = Encoding.UTF8.GetString (result.Buffer);
					if (data.StartsWith (Header, StringComparison.Ordinal)) {
						if (ServerFound != null) {
							var details = new ServerDetails {
								Hostname = result.RemoteEndPoint.Address.ToString (),
								Port = int.Parse (data.Substring (Header.Length))
							};
							LoggingService.LogInfo ("Found TunezServer at {0}", details.FullAddress);
							ServerFound (this, details);
						}
					}
				} catch (ObjectDisposedException) {
					token.ThrowIfCancellationRequested ();
					throw;
				} catch (SocketException) {
					token.ThrowIfCancellationRequested ();
					// Ignore this
				} catch (Exception ex) {
					token.ThrowIfCancellationRequested ();
					LoggingService.LogInfo ("Ignoring bad UDP {0}", ex);
				}
			}
		}
コード例 #60
-1
        static void Main(string[] args)
        {
            System.Net.Sockets.UdpClient sock = new System.Net.Sockets.UdpClient();
            IPEndPoint iep = new IPEndPoint(IPAddress.Parse("129.241.187.44"), 20004);

            Console.WriteLine("Enter message");
            string userinput = Console.ReadLine();
            byte[] data = Encoding.ASCII.GetBytes(userinput);
            sock.Send(data, data.Length, iep);
            sock.Close();

            Console.WriteLine("Message sent.");



            System.Net.Sockets.UdpClient server = new System.Net.Sockets.UdpClient(20004);
            IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0);
            byte[] recvdata = new byte[1024];
            recvdata = server.Receive(ref sender);
            server.Close();
            string stringData = Encoding.ASCII.GetString(recvdata, 0, recvdata.Length);
            Console.WriteLine("Response from " + sender.Address + Environment.NewLine + "Message: " + stringData);
            Console.ReadLine();

        }