C#基于Socket實(shí)現(xiàn)多人聊天功能
本文實(shí)例為大家分享了C#基于Socket實(shí)現(xiàn)多人聊天功能的具體代碼,供大家參考,具體內(nèi)容如下
服務(wù)器
服務(wù)器負(fù)責(zé)接受所有客戶端發(fā)來的消息,和將接受到的問題群發(fā)到其他用戶。
代碼:
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
namespace ChatRoomService
{
? ? class Service
? ? {
? ? ? ? Socket socketSevice ;
? ? ? ? List<Socket> userList;//用戶組
? ? ? ? public Service()
? ? ? ? {
? ? ? ? ? ?socketSevice = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
? ? ? ? ? ?userList = new List<Socket>();
? ? ? ? }
? ? ? ? public void ?Start()
? ? ? ? {
? ? ? ? ? ? socketSevice.Bind(new IPEndPoint(IPAddress.Any,5566));
? ? ? ? ? ? socketSevice.Listen(10);
? ? ? ? ? ? Console.WriteLine("服務(wù)器啟動(dòng)成功");
? ? ? ? ? ? //開啟接受連接,用多線程
? ? ? ? ? ? Thread accThread = new Thread(Accept);
? ? ? ? ? ? accThread.IsBackground = true;
? ? ? ? ? ? accThread.Start();
? ? ? ? }
? ? ? ? private void Accept()
? ? ? ? {
? ? ? ? ? ? //接受連接
? ? ? ? ? ? Socket clientSocket = socketSevice.Accept();
? ? ? ? ? ? userList.Add(clientSocket);
? ? ? ? ? ? //打印已經(jīng)連接IP地址
? ? ? ? ? ? Console.WriteLine(IPToAddress(clientSocket)+"連接進(jìn)來了");
? ? ? ? ? ? //
? ? ? ? ? ? Thread RecvThread = new Thread(ReceMessage);
? ? ? ? ? ? RecvThread.IsBackground = true;
? ? ? ? ? ? RecvThread.Start(clientSocket);
? ? ? ? ? ? Accept();//遞歸
? ? ? ? }
? ? ? ? //接收客戶端信息
? ? ? ? private void ReceMessage(Object obj)
? ? ? ? {
? ? ? ? ? ? Socket client = obj as Socket;
? ? ? ? ? ? byte[] strByte = new byte[1024 * 1024];//設(shè)定接受字符的長度
? ? ? ? ? ? string str = "";
? ? ? ? ? ? try
? ? ? ? ? ? {
? ? ? ? ? ? ? int len = client.Receive(strByte);//接受用戶發(fā)送的內(nèi)容
? ? ? ? ? ? ? str = Encoding.Default.GetString(strByte, 0, len);
? ? ? ? ? ? ? Broadcast(str,client);//廣播給用戶
? ? ? ? ? ? ? Console.WriteLine(str);
? ? ? ? ? ? ?}
? ? ? ? ? ? ?catch (Exception e)
? ? ? ? ? ? ?{
? ? ? ? ? ? ? ? Console.WriteLine(IPToAddress(client)+"退出");
? ? ? ? ? ? ? ? userList.Remove(client);
? ? ? ? ? ? ? ? Thread.CurrentThread.Abort();//退出時(shí)掐死線程,不然遞歸反彈
? ? ? ? ? ? }
? ? ? ? ? ?ReceMessage(client); //使用遞歸
? ? ? ? }
? ? ? ? /// <summary>
? ? ? ? /// 廣播信息
? ? ? ? /// </summary>
? ? ? ? /// <param name="useStr">傳入收到的傳輸?shù)膬?nèi)容</param>
? ? ? ? /// <param name="obj">傳送信息的客戶</param>
? ? ? ? private void Broadcast(string userStr,object obj)
? ? ? ? {
? ? ? ? ? ? Socket clientSend = obj as Socket; //當(dāng)前發(fā)送信息的客戶
? ? ? ? ? ? foreach (Socket client in userList)
? ? ? ? ? ? {
? ? ? ? ? ? ? ? if (client != clientSend)//將信息廣播給其他用戶
? ? ? ? ? ? ? ? {
? ? ? ? ? ? ? ? ? ? client.Send(Encoding.Default.GetBytes(IPToAddress(clientSend)+":"+userStr));
? ? ? ? ? ? ? ? }
? ? ? ? ? ? }
? ? ? ? }? ? ? ? //轉(zhuǎn)換出連來客戶的IP地址
? ? ? ? private string IPToAddress(Socket soket)
? ? ? ? {
? ? ? ? ? ? return (soket.RemoteEndPoint as IPEndPoint).Address.ToString();
? ? ? ? }
? ? }
}using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ChatRoomService
{
? ? class Program
? ? {
? ? ? ? static void Main(string[] args)
? ? ? ? {
? ? ? ? ? ? Service ss = new Service();
? ? ? ? ? ? ss.Start();
? ? ? ? ? ? Console.ReadLine();
? ? ? ? }
? ? }
}客戶端
客戶端的功能開始十分簡單,可以發(fā)送信息給服務(wù)器。也可以接收服務(wù)器轉(zhuǎn)發(fā)過來其他客戶端的信息。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace ChatRoom
{
? ? class ClientRoom
? ? {
? ? ? ? Socket clientSocket;
? ? ? ? public ClientRoom()
? ? ? ? {
? ? ? ? ? ? clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);//初始化服務(wù)器
? ? ? ? }
? ? ? ? /// <summary>
? ? ? ? /// 連接服務(wù)器
? ? ? ? /// </summary>
? ? ? ? /// <param name="Ip"></param>
? ? ? ? /// <param name="port"></param>
? ? ? ? public void Connected(string Ip,int port)
? ? ? ? {
? ? ? ? ? ? clientSocket.Connect(Ip,port);
? ? ? ? ? ? Console.WriteLine("連接成功");
? ? ? ? ? ? // ClientSocket.Bind(new IPEndPoint());
? ? ? ? ? ? Thread RecvThread = new Thread(RecvMessage);
? ? ? ? ? ? RecvThread.IsBackground = true;
? ? ? ? ? ? RecvThread.Start();
? ? ? ? }
? ? ? ?public void Send(String str)
? ? ? ? {
? ? ? ? ? ? clientSocket.Send(Encoding.Default.GetBytes(str));
? ? ? ? }
? ? ? ? /// <summary>
? ? ? ? /// 接受信息
? ? ? ? /// </summary>
? ? ? ? private void RecvMessage()
? ? ? ? {
? ? ? ? ? ? try
? ? ? ? ? ? {
? ? ? ? ? ? ? ? byte[] strByte = new byte[500 * 1024];
? ? ? ? ? ? ? ? int len = clientSocket.Receive(strByte);
? ? ? ? ? ? ? ? Console.WriteLine(Encoding.Default.GetString(strByte, 0, len));
? ? ? ? ? ? }
? ? ? ? ? ? catch (Exception e) //服務(wù)器關(guān)閉
? ? ? ? ? ? {
? ? ? ? ? ? ? ? Console.WriteLine("服務(wù)器關(guān)閉");
? ? ? ? ? ? ? ? Thread.CurrentThread.Abort();//關(guān)閉時(shí)切斷進(jìn)程
? ? ? ? ? ? }
? ? ? ? ? ? RecvMessage();
? ? ? ? } ? ? ? ?
? ? }
}using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ChatRoom
{
? ? class Program
? ? {
? ? ? ? static void Main(string[] args)
? ? ? ? {
? ? ? ? ? ? ClientRoom client = new ClientRoom();
? ? ? ? ? ? client.Connected("127.0.0.1", 5566);
? ? ? ? ? ? string str = Console.ReadLine();
? ? ? ? ? ? while (!str.Equals("q"))
? ? ? ? ? ? {
? ? ? ? ? ? ? ? client.Send(str);
? ? ? ? ? ? ? ? str = Console.ReadLine();
? ? ? ? ? ? }
? ? ? ? ? ? Console.ReadLine();
? ? ? ? }
? ? }
}可以正常對(duì)話,測試一下。假裝和自己對(duì)話

目前還沒有解決沾包問題
以上就是本文的全部內(nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
C#實(shí)現(xiàn)復(fù)制數(shù)據(jù)庫 C#將A數(shù)據(jù)庫數(shù)據(jù)轉(zhuǎn)到B數(shù)據(jù)庫
這篇文章主要為大家詳細(xì)介紹了C#復(fù)制數(shù)據(jù)庫,將數(shù)據(jù)庫數(shù)據(jù)轉(zhuǎn)到另一個(gè)數(shù)據(jù)庫,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-11-11
C#利用IDbDataAdapter/IDataReader實(shí)現(xiàn)通用數(shù)據(jù)集獲取
這篇文章主要為大家詳細(xì)介紹了C#利用IDbDataAdapter/IDataReader實(shí)現(xiàn)通用數(shù)據(jù)集獲取的相關(guān)知識(shí),感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下2024-11-11
利用C#與PLC通信實(shí)現(xiàn)設(shè)備遠(yuǎn)程控制與管理
PLC是工業(yè)自動(dòng)化中用于控制機(jī)械設(shè)備、生產(chǎn)線等的核心設(shè)備,通過與PLC的通信,我們可以實(shí)現(xiàn)設(shè)備的遠(yuǎn)程監(jiān)控、數(shù)據(jù)采集等功能,C#作為一種現(xiàn)代化的編程語言,能夠非常方便地與PLC進(jìn)行通信,本文將介紹如何利用C#與PLC進(jìn)行通信,并實(shí)現(xiàn)設(shè)備的遠(yuǎn)程控制與管理2025-02-02
C#使用隊(duì)列(Queue)解決簡單的并發(fā)問題
這篇文章主要介紹了使用隊(duì)列(Queue)解決簡單的并發(fā)問題,講解的很細(xì)致,喜歡的朋友們可以了解一下2015-07-07

