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

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM