Get the App
SLTechnology News&Howtos  ›  Development  › 

How to realize Multi-person chat function based on Socket in C #

Shulou Source: shulou.com Published: 2022-06-01 18:31:46 10月05日 Update

This article mainly introduces how to achieve multi-person chat function based on Socket in C#. It is very detailed and has a certain reference value. Interested friends must finish reading it!

The details are as follows

Server

The server is responsible for receiving all messages from the client and sending the received problems to other users in groups.

Code:

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 userList;// user group public Service () {socketSevice = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); userList = new List () } public void Start () {socketSevice.Bind (new IPEndPoint (IPAddress.Any,5566)); socketSevice.Listen (10); Console.WriteLine ("Server started successfully"); / / Open accept connection with multithreaded Thread accThread = new Thread (Accept); accThread.IsBackground = true; accThread.Start () } private void Accept () {/ / accept connection Socket clientSocket = socketSevice.Accept (); userList.Add (clientSocket); / / print the connected IP address Console.WriteLine (IPToAddress (clientSocket) + "connected"); / / Thread RecvThread = new Thread (ReceMessage) RecvThread.IsBackground = true; RecvThread.Start (clientSocket); Accept (); / / Recursive} / / receive client information private void ReceMessage (Object obj) {Socket client = obj as Socket; byte [] strByte = new byte [1024 * 1024]; / / set the length of accepted characters string str = "" Try {int len = client.Receive (strByte); / / accept content sent by users str = Encoding.Default.GetString (strByte, 0, len); Broadcast (str,client); / / broadcast to users Console.WriteLine (str) } catch (Exception e) {Console.WriteLine (IPToAddress (client) + "exit"); userList.Remove (client); Thread.CurrentThread.Abort (); / / choke the thread on exit, otherwise recursively bounce} ReceMessage (client) / / customer private void Broadcast (string userStr,object obj) {Socket clientSend = obj as Socket using recursive} / broadcast information / pass in the received transmitted content / transmit the information / / customer foreach (Socket client in userList) {if (client! = clientSend) / / broadcast the information to other users {client.Send (Encoding.Default.GetBytes (IPToAddress (clientSend) + ":" + userStr)) } / / translate the IP address of the connected customer 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 ();} client

The function of the client is very simple at first, and it can send information to the server. You can also receive information from other clients forwarded by the server.

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) / / initialize the server} / connect to the server / public void Connected (string Ip,int port) {clientSocket.Connect (Ip,port); Console.WriteLine ("connected successfully"); / / 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)) } / accept information / private void RecvMessage () {try {byte [] strByte = new byte [1024]; int len = clientSocket.Receive (strByte); Console.WriteLine (Encoding.Default.GetString (strByte, 0, len)) } catch (Exception e) / / Server shuts down {Console.WriteLine ("server shutdown"); Thread.CurrentThread.Abort (); / / shuts off the process} 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 ();}

You can have a normal conversation and test it. Pretend to talk to yourself.

At present, the problem of bag contamination has not been solved.

The above is all the contents of the article "how to achieve multi-person chat based on Socket in C#". Thank you for reading! Hope to share the content to help you, more related knowledge, welcome to follow the industry information channel!

Tags: Server service information client content user function client recursion broadcast multi-person clientele success address end article thread question conversation code Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno vpn Microsoft Huawei Shulou Technology MariaDB