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


C# UdpClient.Close方法代码示例

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


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

示例1: IPEndPoint

        /*
        // 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();

            }
        }
开发者ID:IlyichTrue,项目名称:NetSend,代码行数:74,代码来源:NetworkBasic.cs

示例2: transfer

        /*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;
        }
开发者ID:vnwhlr,项目名称:Schoolwork,代码行数:57,代码来源:TFTP.cs

示例3: Send

 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;
 }
开发者ID:itsmevix,项目名称:FTT-DLNA,代码行数:28,代码来源:Datagram.cs

示例4: Discover

        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);
            }
        }
开发者ID:CurlyBrackets,项目名称:DynamicLibrary,代码行数:25,代码来源:RemoteExecutor.cs

示例5: Send

        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();
                }
            }
        }
开发者ID:janusmalone,项目名称:MultiMiner,代码行数:33,代码来源:Sender.cs

示例6: TestConnectAsync_Success

		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();
			}
		}
开发者ID:Indifer,项目名称:Test,代码行数:28,代码来源:UdpClientTransportManagerTest.cs

示例7: StopUDPClient

 /// <summary>
 /// Stops the UDP client.
 /// </summary>
 /// <param name="udpClient">The UDP client.</param>
 public static void StopUDPClient(UdpClient udpClient)
 {
     if (udpClient != null)
     {
         udpClient.Close();
     }
 }
开发者ID:andreigec,项目名称:ANDREICSLIB,代码行数:11,代码来源:Networking.cs

示例8: GetFromTrial

        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
        }
开发者ID:rc153,项目名称:LTF,代码行数:27,代码来源:MTU.cs

示例9: HandleBroadcasts

        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();
        }
开发者ID:bdr27,项目名称:c-,代码行数:26,代码来源:MainWindow.xaml.cs

示例10: Main

        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
        }
开发者ID:jonathankellermann,项目名称:UDP_Server,代码行数:27,代码来源:Program.cs

示例11: Main

        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();
        }
开发者ID:RavenXce,项目名称:PowerWiFlyII,代码行数:26,代码来源:Program.cs

示例12: Worker

        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;
            }

        }
开发者ID:gbcwbz,项目名称:ModbusTool,代码行数:30,代码来源:UDPBroadcaster.cs

示例13: checkCapacity

        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();
                }

            }
        }
开发者ID:wongtseng,项目名称:RFGIS,代码行数:30,代码来源:ClientSocket.cs

示例14: Send

 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;
 }
开发者ID:vitska,项目名称:simpleDLNA,代码行数:30,代码来源:Datagram.cs

示例15: backgroundWorker1_DoWork

        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();
        }
开发者ID:GT-Deck,项目名称:StarMade-Remote-Start-Server,代码行数:35,代码来源:Form1.cs


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