溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

C#如何使用Socket實(shí)現(xiàn)本地多人聊天室

發(fā)布時(shí)間:2022-02-11 10:27:51 來源:億速云 閱讀:147 作者:小新 欄目:開發(fā)技術(shù)

這篇文章主要介紹C#如何使用Socket實(shí)現(xiàn)本地多人聊天室,文中介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們一定要看完!

【腳本一:Server端】

使用本機(jī)地址:127.0.0.1

完整代碼

using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
 
namespace ConsoleApp1
{
    public class Server
    {
        Socket mySocket = null;
        Dictionary<IPAddress, Socket> cliDic = new Dictionary<IPAddress, Socket>();
 
        public void Connect(int port)
        {
            string IP = "127.0.0.1";
            //IPAddress IPAddress = IPAddress.Parse("127.0.0.1");
            IPAddress address = IPAddress.Any;
            //創(chuàng)建IP終結(jié)點(diǎn),把IP地址與端口綁定到網(wǎng)絡(luò)終結(jié)點(diǎn)上
            IPEndPoint endPoint = new IPEndPoint(address, port);
            //創(chuàng)建客戶端套接字
            mySocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            ///監(jiān)聽套接字終結(jié)點(diǎn)
            mySocket.Bind(endPoint);
            //服務(wù)端可接收客戶端連接數(shù)量為無限個(gè)
            mySocket.Listen(0);
            //開啟線程監(jiān)聽客戶端
            Thread myThread = new Thread(Listen_Con);
            myThread.Start();
            Console.WriteLine("開始監(jiān)聽...");
        }
 
        /// <summary>
        /// 接收連接的客戶端并存儲客戶端的信息
        /// </summary>
        /// <param name="obj"></param>
        public void Listen_Con(Object obj)
        {
            Socket cliSocket = null;
            //持續(xù)監(jiān)聽客戶端的請求
            while (true)
            {
                try
                {
                    cliSocket = mySocket.Accept();
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.Message);
                }
                string cliEndPoint = cliSocket.RemoteEndPoint.ToString();
                IPAddress cliAddress = (cliSocket.RemoteEndPoint as IPEndPoint).Address;
                int cliPort = (cliSocket.RemoteEndPoint as IPEndPoint).Port;
                cliDic.Add(cliAddress, cliSocket);
                string MsgStr = "[客戶端結(jié)點(diǎn):" + cliEndPoint + "\n+客戶端IP:" + cliAddress.ToString() + "\n客戶端端口:" +
                    cliPort.ToString() + "\n已連接]";
                byte[] MsgBytes = Encoding.UTF8.GetBytes(MsgStr);
                cliSocket.Send(MsgBytes);
 
                Thread rec_Cli = new Thread(Receive_Con);
                rec_Cli.Start(cliSocket);
                Thread sed_Cli = new Thread(SendToCli);
                sed_Cli.Start(cliSocket);
            }
        }
 
        /// <summary>
        /// 接收已連接的客戶端發(fā)送的消息
        /// </summary>
        /// <param name="socket"></param>
        public void Receive_Con(Object socket)
        {
            Socket client = socket as Socket;
            while (true)
            {
                //創(chuàng)建大小為1024*1024的內(nèi)存緩沖區(qū)(1M)
                byte[] recBytes = new byte[1024 * 1024];
                //嘗試把接收的字節(jié)存儲到緩沖區(qū)
                try
                {
                    int length = client.Receive(recBytes);
                    //把機(jī)器接收的字節(jié)數(shù)組轉(zhuǎn)換為string
                    string recMsg = Encoding.UTF8.GetString(recBytes, 0, length);
                    //將服務(wù)器接收到的信息轉(zhuǎn)發(fā)到所有已連接的客戶端
                    if (cliDic.Count > 0)
                    {
                        foreach (var soc in cliDic)
                        {
                            soc.Value.Send(Encoding.UTF8.GetBytes("[" + soc.Value.RemoteEndPoint + "]:" + recMsg));
                        }
                    }
                    Console.WriteLine("[" + client.RemoteEndPoint + "]:" + recMsg);
                }
                catch (Exception)
                {
                    cliDic.Remove((client.RemoteEndPoint as IPEndPoint).Address);
                    //客戶端斷開的異常
                    Console.WriteLine("[客戶端" + (client.RemoteEndPoint as IPEndPoint).Address + "已斷開]");
                    Console.WriteLine("[客戶端終結(jié)點(diǎn):" + client.RemoteEndPoint+"]");
                    //斷開套接字
                    client.Close();
                    break;
                }
            }
        }
 
        public void SendToCli(object obj)
        {
            Socket curCliSoc = obj as Socket;
            while (true)
            {
                byte[] ByteToAll = new byte[1024 * 1024];
                try
                {
                    string MsgToAll = Console.ReadLine();
                    ByteToAll = Encoding.UTF8.GetBytes("[服務(wù)端]:"+MsgToAll);
                    curCliSoc.Send(ByteToAll);
                }
                catch(Exception)
                {
                    Console.WriteLine("ERROR:" + curCliSoc.RemoteEndPoint + "已與服務(wù)端斷開!");
                    curCliSoc.Close();
                    if(cliDic.ContainsKey((curCliSoc.RemoteEndPoint as IPEndPoint).Address))
                    {
                        cliDic.Remove((curCliSoc.RemoteEndPoint as IPEndPoint).Address);
                    }
                }
            }
        }
    }
 
    public class ServerMain
    {
        static void Main(string[] args)
        {
            Server s1 = new Server();
            s1.Connect(8800);
        }
    }
}

Server端運(yùn)行結(jié)果:

C#如何使用Socket實(shí)現(xiàn)本地多人聊天室

【腳本二:Client端】

完整代碼

using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
 
namespace ConsoleApp1
{
    public class Client
    {
        string SerIP = "127.0.0.1";
        Socket myClient = null;
        Thread ConnectThread = null;
        IPAddress SerAdd;
        IPEndPoint SerEP;
        public void Connect_To_Ser(int port)
        {
            myClient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            SerAdd = IPAddress.Parse(SerIP);
            SerEP = new IPEndPoint(SerAdd, port);
            while (true)
            {
                try
                {
                    myClient.Connect(SerEP);
                    break;
                }
                catch
                {
                    Console.WriteLine("無法連接到服務(wù)端,請重試...");
                }
            }
            ConnectThread = new Thread(Receive_Ser);
            ConnectThread.Start();
        }
 
        public void Receive_Ser()
        {
            while (true)
            {
                byte[] SerBytes = new byte[1024 * 1024];
                try
                {
                    int length = myClient.Receive(SerBytes);
                    string Msg = Encoding.UTF8.GetString(SerBytes, 0, length);
                    Console.WriteLine(Msg);
                }
                catch (Exception)
                {
                    Console.WriteLine("已與服務(wù)端斷開連接...");
                    break;
                }
            }
        }
 
        public void SendToSer()
        {
            while (true)
            {
                try
                {
                    string SendMsg = Console.ReadLine();
                    myClient.Send(Encoding.UTF8.GetBytes(SendMsg));
                }
                catch (Exception)
                {
                    Console.WriteLine("[SendToSer]已斷開連接");
                    break;
                }
            }
        }
    }
 
    public class ClienMain
    {
        static void Main(string[] Args)
        {
            Client c1 = new Client();
            c1.Connect_To_Ser(8800);
            c1.SendToSer();
        }
    }
}

客戶端運(yùn)行效果:

①客戶端先于服務(wù)端運(yùn)行

C#如何使用Socket實(shí)現(xiàn)本地多人聊天室

②客戶端遲于服務(wù)端運(yùn)行

C#如何使用Socket實(shí)現(xiàn)本地多人聊天室

暫時(shí)總效果:

C#如何使用Socket實(shí)現(xiàn)本地多人聊天室

以上是“C#如何使用Socket實(shí)現(xiàn)本地多人聊天室”這篇文章的所有內(nèi)容,感謝各位的閱讀!希望分享的內(nèi)容對大家有幫助,更多相關(guān)知識,歡迎關(guān)注億速云行業(yè)資訊頻道!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI