Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use Socket to realize local multi-person chat room in C #

2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly introduces how to use Socket to achieve a local multi-person chat room in C#. It is very detailed and has a certain reference value. Interested friends must read it!

[script 1: server]

Use the local address: 127.0.0.1

Complete code

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 cliDic = new Dictionary (); public void Connect (int port) {string IP = "127.0.0.1"; / / IPAddress IPAddress = IPAddress.Parse ("127.0.0.1") IPAddress address = IPAddress.Any; / / create the IP endpoint, bind the IP address and port to the network endpoint IPEndPoint endPoint = new IPEndPoint (address, port); / / create the client socket mySocket = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); / / listen on the socket endpoint mySocket.Bind (endPoint) / / the server can receive an unlimited number of mySocket.Listen (0) client connections; / / Open the thread listening client Thread myThread = new Thread (Listen_Con); myThread.Start (); Console.WriteLine ("start listening...") } / receive the connected client and store the client's information / public void Listen_Con (Object obj) {Socket cliSocket = null / / continuously monitor client requests 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 = "[client node:" + cliEndPoint + "\ n + client IP:" + cliAddress.ToString () + "\ nclient port:" + cliPort.ToString () + "\ nconnected]"; 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) }} / receive a message from a connected client / public void Receive_Con (Object socket) {Socket client = socket as Socket While (true) {/ / create a memory buffer (1m) byte [] recBytes = new byte [1024024]; / / attempt to store the received bytes in the buffer try {int length = client.Receive (recBytes) / / convert the byte array received by the machine to string string recMsg = Encoding.UTF8.GetString (recBytes, 0, length) / / forward the information received by the server to all connected clients 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) / / client disconnected exception Console.WriteLine ("[client" + (client.RemoteEndPoint as IPEndPoint). Address + "disconnected]"); Console.WriteLine ("[client endpoint:" + client.RemoteEndPoint+ "]"); / / disconnect socket 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 ("[server]:" + MsgToAll); curCliSoc.Send (ByteToAll) } catch (Exception) {Console.WriteLine ("ERROR:" + curCliSoc.RemoteEndPoint + "disconnected from the server!") ; 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);}

The result of running on Server:

[script 2: client side]

Complete code

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 ("unable to connect to the server, please try again");}} 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 ("disconnected from server..."); break } public void SendToSer () {while (true) {try {string SendMsg = Console.ReadLine (); myClient.Send (Encoding.UTF8.GetBytes (SendMsg)) } catch (Exception) {Console.WriteLine ("[SendToSer] disconnected"); break;}} public class ClienMain {static void Main (string [] Args) {Client C1 = new Client () C1.Connect_To_Ser (8800); c1.SendToSer ();}

Client running effect:

The ① client runs before the server

The ② client runs later than the server

Temporary total effect:

The above is all the content of the article "how to implement a local multi-person chat room with 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!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report