c#網(wǎng)絡(luò)編程-聊天小程序

服務(wù)器模塊

sever部分

server2.cs

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

namespace ConsoleApp8
{
    class Sever2
    {
        private Socket serverSocket;
        private List<Socket> clientList;//存儲(chǔ)連進(jìn)來的客戶端
        //構(gòu)造函數(shù)
        public Sever2()
        {
            serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            clientList = new List<Socket>();//連一個(gè)客戶端往里面加一個(gè)
        }
        //啟動(dòng)函數(shù)
        public void Start()
        {
            serverSocket.Bind(new IPEndPoint(IPAddress.Any, 12305));
            serverSocket.Listen(10);
            Console.WriteLine("服務(wù)器啟動(dòng)成功!");

            Thread threadAccept = new Thread(Accept);
            threadAccept.IsBackground = true;
            threadAccept.Start();
        }
        private void Accept()
        {
            //接收客戶端的方法,會(huì)掛起當(dāng)前線程
            Socket client = serverSocket.Accept();
            IPEndPoint ipPoint = client.RemoteEndPoint as IPEndPoint;
            Console.WriteLine($"{ipPoint.Address} [{ipPoint.Port}]連接成功!");
            clientList.Add(client);

            Thread threadReceive = new Thread(Receive);
            threadReceive.IsBackground = true;
            threadReceive.Start(client);

            Accept();
        }
        private void Receive(object obj)
        {
            Socket client =obj as Socket;
            IPEndPoint ipPoint = client.RemoteEndPoint as IPEndPoint;
            try
            {
                byte[] msg = new byte[1024];
                int msgLen = client.Receive(msg);
                String msgStr = $"{ipPoint.Address}[{ipPoint.Port}] 說: {Encoding.UTF8.GetString(msg, 0, msgLen)}";
                Console.WriteLine(msgStr);
                Broadcast(client, msgStr);
                //服務(wù)器往客戶端發(fā)消息
                //client.Send(Encoding.UTF8.GetBytes(Encoding.UTF8.GetString(msg, 0, msgLen) + "-樓上說的對(duì)"));

                Receive(client);//尾遞歸

            }
            catch
            {
                string catchStr = $"{ipPoint.Address}[{ipPoint.Port}]斷開";
                Console.WriteLine(catchStr);
                Broadcast(client, catchStr);
                clientList.Remove(client);
            }
        }
        private void Broadcast(Socket clientOther, string msg)
        {
            foreach(var item in clientList)
            {
                if(item==clientOther)
                {
                    //同一客戶端,無需響應(yīng)
                }
                else
                {
                    item.Send(Encoding.UTF8.GetBytes(msg));
                }
            }
        }
    }
}

主程序部分

Program.cs

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

namespace ConsoleApp8
{
    class Program
    {
        static void Main(string[] args)
        {
            Sever2 sever2 = new Sever2();
            sever2.Start();
            Console.ReadKey();
        }
    }
}

客戶端模塊

client部分

ClientSocket.cs

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

namespace Client2
{
    class ClientSocket
    {
        private Socket clientSocket;
        public ClientSocket()
        {
            clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            //構(gòu)造函數(shù)
        }
        public void Connect(string ip, int port)
        {
            clientSocket.Connect(ip,port);
            Console.WriteLine("連接服務(wù)器成功!");

            Thread ReceiveThread = new Thread(Receive);
            ReceiveThread.IsBackground = true;
            ReceiveThread.Start();
        }
        private void Receive()
        {
            try
            {
                byte[] msg = new byte[1024];
                int msgLen = clientSocket.Receive(msg);
                Console.WriteLine($"{Encoding.UTF8.GetString(msg, 0, msgLen)}");
                Receive();
            }
            catch
            {
                Console.WriteLine("服務(wù)器斷開");
            }
        }
        public void send(string msg)
        {
            clientSocket.Send(Encoding.UTF8.GetBytes(msg));
        }
    }
}

主程序部分

Program.cs

using System;

namespace Client2
{
    class Program
    {
        static void Main(string[] args)
        {
            ClientSocket client2 = new ClientSocket();
            client2.Connect("127.0.0.1", 12305);

            Console.WriteLine("請(qǐng)輸入要發(fā)送的內(nèi)容,輸入quit退出");
            string msg = Console.ReadLine();
            while(msg!="quit")
            {
                client2.send(msg);
                msg = Console.ReadLine();
            }

            Console.ReadKey();
        }
    }
}

結(jié)果

Snipaste_2019-11-29_17-25-13.png
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容