zoukankan      html  css  js  c++  java
  • C#网络编程学习(2)---Socket之Udp协议的简单使用

    使用Udp协议实现最简单的服务器与客户端通信

    1、服务器端

            public static Socket udpServer;
            static void Main(string[] args)
            {
                //1. 创建socket
                udpServer = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
    
                //2. 绑定ip和端口号
                udpServer.Bind(new IPEndPoint(IPAddress.Parse("192.168.1.2"), 6666));
    
                //3. 接收数据
                //因为要一直接收所以单独设置一个线程。
                //当程序结束时,不再接收,所以设置为后台线程
                new Thread(ReceiveMessage) {IsBackground = true}.Start();
    
                Console.ReadKey();
            }
    
            static void ReceiveMessage()
            {
                //3. 接收数据
                while (true)
                {
                    EndPoint point = new IPEndPoint(IPAddress.Any, 0); //ip和端口号都不需要赋值
                    byte[] data = new byte[1024];
                    int length = udpServer.ReceiveFrom(data, ref point); //这个方法会把数据的来源(ip,端口号),放在第二个参数上
    
                    string message = Encoding.UTF8.GetString(data, 0, length);
                    Console.WriteLine("从ip:" + (point as IPEndPoint).Address.ToString() + "端口号:" +
                                      (point as IPEndPoint).Port.ToString() + "收到了数据:" + message);
                }
    
            }
    

    2、客户端

            static void Main(string[] args)
            {
                //1.创建socket
                Socket udpClient = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
    
    
                //3.向服务器发送消息
                EndPoint point = new IPEndPoint(IPAddress.Parse("192.168.1.2"), 6666);
                byte[] data = Encoding.UTF8.GetBytes("Hello I am Ffly");
                udpClient.SendTo(data, point);
    
                Console.ReadKey();
            }
    

    3、效果

    1. 先运行服务器窗口
    2. 再运行客户端窗口
    3. 在服务器的窗口上会显示客户端的连接消息
  • 相关阅读:
    转载的log4cplus使用指南
    linux下安装log4cplus
    MongoDB常用命令
    ios UIButton改背景
    ios发送邮件
    oracle数据库 in 结果字段的拆分
    Server returned HTTP response code: 505
    ORA-01795:列表中的最大表达式数为1000
    ajax post请求
    oracle 同义词
  • 原文地址:https://www.cnblogs.com/Fflyqaq/p/10827669.html
Copyright © 2011-2022 走看看