C# UDP聊天室简单实现

服务端:

using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Net;
using System.Net.Sockets;


namespace SocketUDP_Server
{
    /// <summary>
    /// 服务端
    /// </summary>
    class Program
    {
        private static int Port = 8848;

        private static Socket socket;
        private static IPEndPoint ServerIPPort;   //服务器侦听的IP范围和端口

        private static List<IPEndPoint> ClientPoints = new List<IPEndPoint>();     //所有和服务器链接的客户端
        private static void Main(string[] args)
        {

            ServerIPPort = new IPEndPoint(IPAddress.Any, Port);     //服务器侦听所有IP和本机8848端口
            //定义套接字类型,在主线程中定义
            socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            //Socket绑定服务器端
            socket.Bind(ServerIPPort);

            Console.WriteLine("服务器初始化完成...");

            Thread ReceiveClient = new Thread(SocketReceive);
            ReceiveClient.Start();

            Console.ReadKey();
        }


        /// <summary>
        /// 服务器持续接收信息
        /// </summary>
        private static void SocketReceive()
        {
            //进入接收循环
            while (true)
            {
                //定义字节组并且设定长度
                byte[] recvData = new byte[1024];
                //recvData的临时长度
                int recvDataLength = 0;

                IPEndPoint ClientTemp = new IPEndPoint(IPAddress.Any, 0);   //初始化一个临时的客户端类
                EndPoint Client = (EndPoint)ClientTemp;     //链接到服务器的客户端(临时的)
                recvDataLength = socket.ReceiveFrom(recvData, ref Client);  //ReceiveFrom侦听方法
                
                addToClientPoints((IPEndPoint)Client);
                
                //输出接收到的数据
                string TempStr = Encoding.UTF8.GetString(recvData, 0, recvDataLength);
                Console.WriteLine("客户端-" + Client.ToString() + ":"+ TempStr);


                //向其它客户端进行信息广播
                sendToAllClient((IPEndPoint)Client, Encoding.UTF8.GetBytes(Client.ToString() + ":" + TempStr));

                //Console.WriteLine(ClientPoints.Count);

            }
        }
        
        /// <summary>
        /// 添加到客户端集合逻辑
        /// </summary>
        private static void addToClientPoints(IPEndPoint Client)
        {
            //通过字符串判断是否和现有的"IPEndPoint"重复
            bool key = true;
            for (int i = 0; i < ClientPoints.Count; i++)
            {
                if(ClientPoints[i].ToString() == Client.ToString())
                {
                    key = false;
                    break;
                }
            }
            if(key == true)
            {
                ClientPoints.Add(Client);
            }

            //遍历所有链接到的客户端信息
            //for (int i = 0; i < ClientPoints.Count; i++)
            //{
            //    Console.WriteLine(ClientPoints[i].ToString());
            //}
        }

        /// <summary>
        /// 给所有客户端发送信息
        /// </summary>
        /// <param name="Client">发出此信息的客户端(避免给此客户端发送信息)</param>
        private static void sendToAllClient(IPEndPoint Client, byte[] messageByte)
        {
            for (int i = 0; i < ClientPoints.Count; i++)
            {
                if (ClientPoints[i].ToString() != Client.ToString())
                {
                    socket.SendTo(messageByte, messageByte.Length, SocketFlags.None, ClientPoints[i]);
                    //Console.WriteLine("转送了");
                }
            }
        }

    }
}

客户端:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Net;
using System.Net.Sockets;

namespace SocketUDP_Client
{
    /// <summary>
    /// 客户端
    /// </summary>
    class Program
    {
        private static IPAddress IP = IPAddress.Parse("62.234.48.162");
        //private static IPAddress IP = IPAddress.Parse("127.0.0.1");
        private static int Port = 8848;
        private static Socket socket;
        private static IPEndPoint ServerIPPort;   //服务器侦听的IP范围和端口
        
        private static IPEndPoint ClientReceiveIPPort;   //客户端侦听服务器
        private static EndPoint Client;
        

        private static void Main(string[] args)
        {
            //初始化Socket
            socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            //连接服务器的IP和端口
            ServerIPPort = new IPEndPoint(IP, Port);
            
            //服务器的地址端
            ClientReceiveIPPort = new IPEndPoint(IPAddress.Any, 0);
            Client = (EndPoint)ClientReceiveIPPort;

            //绑定服务端(客户端只接收服务端发来的信息)
            socket.Bind(Client);

            Console.WriteLine("请输入需要发送的信息:  ↓");
            //Console.WriteLine(socket.LocalEndPoint.ToString());
            
            Thread SendToServer = new Thread(LoopSendMessage);
            SendToServer.Start();

            Thread ReceiveToServer = new Thread(SocketReceive);
            ReceiveToServer.Start();

            Console.ReadKey();
        }


        /// <summary>
        /// 客户端接收服务器发来的其它客户端信息
        /// </summary>
        private static void SocketReceive()
        {
            //进入接收循环
            while (true)
            {
                //定义字节组并且设定长度
                byte[] recvData = new byte[1024];
                //recvData的临时长度
                int recvDataLength = 0;

                try
                {
                    recvDataLength = socket.ReceiveFrom(recvData, ref Client);  //ReceiveFrom侦听方法
                }
                catch
                {
                    Console.WriteLine("与服务器断开链接!!!");
                }
                //输出接收到的数据
                string TempStr = Encoding.UTF8.GetString(recvData, 0, recvDataLength);
                Console.WriteLine(TempStr);
                
            }
        }

        /// <summary>
        /// 循环发送信息
        /// </summary>
        private static void LoopSendMessage()
        {
            //客户端首次向服务器发送信息
            SendMessage("上线了");

            while (true)
            {
                string tempMessage = Console.ReadLine();
                SendMessage(tempMessage);
            }
        }
        
        /// <summary>
        /// 向服务器发送信息
        /// </summary>
        private static void SendMessage(string message)
        {
            //定义要发送的字节组及长度
            byte[] messageByte = new byte[1024];
            //讲字符串转换成字节组
            messageByte = Encoding.UTF8.GetBytes(message);
            //发送到知道的服务器
            socket.SendTo(messageByte, messageByte.Length, SocketFlags.None, ServerIPPort);
        }
    }
}

  

C# UDP聊天室简单实现

上一篇:C#中对于接口的实现方式


下一篇:C#-Forms.Timer、Timers.Timer、Threading.Timer的比较和使用