日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

C#基于Socket實現多人聊天功能_C#教程

作者:以前是少年 ? 更新時間: 2022-04-16 編程語言

本文實例為大家分享了C#基于Socket實現多人聊天功能的具體代碼,供大家參考,具體內容如下

服務器

服務器負責接受所有客戶端發來的消息,和將接受到的問題群發到其他用戶。

代碼:

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("服務器啟動成功");

? ? ? ? ? ? //開啟接受連接,用多線程
? ? ? ? ? ? Thread accThread = new Thread(Accept);
? ? ? ? ? ? accThread.IsBackground = true;
? ? ? ? ? ? accThread.Start();
? ? ? ? }

? ? ? ? private void Accept()
? ? ? ? {
? ? ? ? ? ? //接受連接
? ? ? ? ? ? Socket clientSocket = socketSevice.Accept();
? ? ? ? ? ? userList.Add(clientSocket);
? ? ? ? ? ? //打印已經連接IP地址
? ? ? ? ? ? Console.WriteLine(IPToAddress(clientSocket)+"連接進來了");

? ? ? ? ? ? //
? ? ? ? ? ? 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];//設定接受字符的長度
? ? ? ? ? ? string str = "";
? ? ? ? ? ? try
? ? ? ? ? ? {
? ? ? ? ? ? ? int len = client.Receive(strByte);//接受用戶發送的內容
? ? ? ? ? ? ? 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();//退出時掐死線程,不然遞歸反彈
? ? ? ? ? ? }
? ? ? ? ? ?ReceMessage(client); //使用遞歸
? ? ? ? }

? ? ? ? /// <summary>
? ? ? ? /// 廣播信息
? ? ? ? /// </summary>
? ? ? ? /// <param name="useStr">傳入收到的傳輸的內容</param>
? ? ? ? /// <param name="obj">傳送信息的客戶</param>
? ? ? ? private void Broadcast(string userStr,object obj)
? ? ? ? {
? ? ? ? ? ? Socket clientSend = obj as Socket; //當前發送信息的客戶
? ? ? ? ? ? foreach (Socket client in userList)
? ? ? ? ? ? {
? ? ? ? ? ? ? ? if (client != clientSend)//將信息廣播給其他用戶
? ? ? ? ? ? ? ? {
? ? ? ? ? ? ? ? ? ? client.Send(Encoding.Default.GetBytes(IPToAddress(clientSend)+":"+userStr));
? ? ? ? ? ? ? ? }
? ? ? ? ? ? }
? ? ? ? }? ? ? ? //轉換出連來客戶的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();
? ? ? ? }
? ? }
}

客戶端

客戶端的功能開始十分簡單,可以發送信息給服務器。也可以接收服務器轉發過來其他客戶端的信息。

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);//初始化服務器
? ? ? ? }
? ? ? ? /// <summary>
? ? ? ? /// 連接服務器
? ? ? ? /// </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) //服務器關閉
? ? ? ? ? ? {
? ? ? ? ? ? ? ? Console.WriteLine("服務器關閉");
? ? ? ? ? ? ? ? Thread.CurrentThread.Abort();//關閉時切斷進程
? ? ? ? ? ? }
? ? ? ? ? ? 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();
? ? ? ? }
? ? }
}

可以正常對話,測試一下。假裝和自己對話

目前還沒有解決沾包問題

原文鏈接:https://blog.csdn.net/qq_38061677/article/details/81226818

欄目分類
最近更新