注册 登录
编程论坛 C# 论坛

udpclient类的应用实例

weiwei2023 发布于 2023-04-12 13:06, 922 次点击
using System;
using
using
using System.Text;
namespace UdpClientServer
{
    class class1
    {
        static void Main()
        {
            StarListener();
            Console.ReadLine();
        }
        private static void StarListener()
        {
            UdpClient udpServer=new UdpClient(8000);
            IPEndPoint myHost=null;
            {
                while(true)
                {
                    try
                    Console.WriteLine("等待接受...");
                    byte[]getBytes=udpServer.Receive(ref myHost);
                    string getString=Encoding.Unicode.GetString(getBytes,0,getBytes.Length);
                    Console.WriteLine("接受信息:{0}",getString);
                    if(getString=="quite")break;
                    string sendString="你好,多保重!";
                    Console,WriteLine("发送消息:{0}",sendString);
                    byte[]sendBytes=Encoding.Unicode.GetBytes(sendString);
                    udpServer.Send(sendBytes,sendBytes.Length,"127.0.0.1",8001);
                }
                udpServer.Close();
                Console.WriteLine("对方已经退出,请按回车键退出。");
            }
            catch(Exception err)
            {
                Console.WriteLine(err.ToString());
            }
        }
    }
}
1 回复
#2
东海ECS2023-04-16 10:20
一个简单的UDP服务器,监听本地8000端口,并接受来自客户端的消息,然后回复一个固定的消息:“你好,多保重!”。运行程序,并在命令行中输入“quite”来停止程序。
1