C # implement a multi-threaded LAN chat system

Source: Internet
Author: User

C # implement a multi-threaded LAN chat system

This article mainly introduces the code for Implementing the multi-threaded LAN chat system in c #. For more information, see.

I think it is helpful.

Socke programming, supports multiple clients, multi-threaded operations to avoid endless boundaries.

Enable socket

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

Private void button#click (object sender, EventArgs e)

{

Try

{

Int port = int. Parse (txt_port.Text );

String host = txt_ip.Text;

// Create an endpoint

IPAddress ip = IPAddress. Parse (host );

IPEndPoint ipe = new IPEndPoint (ip, port );

// Create a Socket and start listening

Newsock = new Socket (AddressFamily. InterNetwork, SocketType. Stream, ProtocolType. Tcp); // create a Socket object. If UDP is used, use a Socket of the SocketTyype. Dgram type.

Newsock. Bind (ipe); // Bind an EndPoint object

Newsock. Listen (0); // start listening

// Create a new Socket for the newly established connection

AcceptClientThread = new Thread (new ThreadStart (AcceptClient ));

AcceptClientThread. Start ();

SetText ("Start listening ");

}

Catch (Exception exp)

{

CommonFunction. WriteLog (exp, exp. Message );

}

}

Monitoring Port, receiving Client

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

/// <Summary>

/// Accept the client. Multiple clients can be connected simultaneously and registered to the client list.

/// </Summary>

Public void AcceptClient ()

{

Try

{

While (true)

{

Socket client = newsock. Accept ();

Ip = client. Handle;

RegeistUser (client. Handle, client );

Thread clientThread = new Thread (new ParameterizedThreadStart (ReceiveData ));

Object o = client;

ClientThread. Start (o );

}

}

Catch (Exception exp)

{

CommonFunction. WriteLog (exp, exp. Message );

}

}

Receive client data and broadcast data

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

/// <Summary>

/// Receives and forwards the client data to the target client.

/// </Summary>

Public void ReceiveData (object o)

{

Try

{

While (true)

{

Socket client = (Socket) o;

String recvStr = "";

Byte [] recvBytes = new byte [1, 1024];

Int bytes;

Bytes = client. Receive (recvBytes, recvBytes. Length, 0); // Receive messages from the client

RecvStr = Encoding. UTF8.GetString (recvBytes, 0, bytes );

SendMessage (client, recvStr );

SetText (recvStr );

CommonFunction. WriteErrorLog (recvStr );

}

}

Catch (Exception exp)

{

CommonFunction. WriteLog (exp, exp. Message );

}

}

Determine whether to register a user or send a message

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

/// <Summary>

/// Determine whether to register a user or send a message

/// </Summary>

/// <Param name = "p_strMessage"> </param>

Public void SendMessage (Socket client, string p_strMessage)

{

If (p_strMessage.StartsWith ("@"))

{

RegeistUser (p_strMessage, client );

}

Else if (p_strMessage.StartsWith ("> "))

{

 

Deletecreceivent (p_strMessage );

}

Else

{

// SendMessageToTarget (p_strMessage );

SendAllMessage (p_strMessage );

}

}

Register the socket as the specified user name

?

1

2

3

4

5

6

7

8

9

10

11

12

/// <Summary>

/// Register the socket as the specified user name

/// </Summary>

/// <Param name = "user"> </param>

/// <Param name = "ss"> </param>

Public void RegeistUser (string user, Socket ss)

{

User = user. Remove (0, 1 );

UserSocketDict. Add (user, ss );

SendOneMessage (ss, "welcome" + user + "connected! ");

RefreshClient ();

}

Remove a client from the client dictionary

?

1

2

3

4

5

6

7

8

9

10

/// <Summary>

/// Remove the client from the client dictionary

/// </Summary>

/// <Param name = "p_strMessage"> </param>

Public void DeleteClident (string p_strMessage)

{

P_strMessage = p_strMessage.Remove (0, 1 );

UserSocketDict. Remove (p_strMessage );

RefreshClient ();

}

Send Group messages

?

1

2

3

4

5

6

7

8

9

10

11

12

13

/// <Summary>

/// Send Group messages

/// </Summary>

/// <Param name = "p_strsend"> </param>

Public void SendAllMessage (string p_strsend)

{

// MessageBox. Show (p_strsend );

Foreach (string item in userSocketDict. Keys)

{

Byte [] bs = Encoding. UTF8.GetBytes (p_strsend );

UserSocketDict [item]. Send (bs, bs. Length, 0 );

}

}

Assign a value to the text box

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

Public delegate void SetTextHandler (string text );

/// <Summary>

/// Assign a value to the text box

/// </Summary>

/// <Param name = "text"> </param>

Private void SetText (string text)

{

If (rich_back.InvokeRequired = true)

{

SetTextHandler set = new SetTextHandler (SetText); // the delegate's method parameters should be consistent with SetText

Rich_back.Invoke (set, new object [] {text}); // The second parameter of this method is used to pass in the method, instead of text

}

Else

{

Rich_back.Text + = "\ n" + text;

}

 

}

Connect to the server

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

Private void button#click (object sender, EventArgs e)

{

Try

{

User = txt_name.Text;

Int port = int. Parse (txt_port.Text );

String host = txt_ip.Text;

// Create an EndPoint

IPAddress ip = IPAddress. Parse (host );

IPEndPoint ipe = new IPEndPoint (ip, port); // converts the ip address and port to an instance of IPEndPoint.

// Create a Socket and connect to the server

Socket c = new Socket (AddressFamily. InterNetwork, SocketType. Stream, ProtocolType. Tcp); // create a Socket

Cc = c;

C. Connect (ipe); // Connect to the server

ClientThread = new Thread (new ThreadStart (ReceiveData ));

ClientThread. Start ();

// Send the local user name to the server so that the server can register the client

SendMessage ("@" + txt_name.Text );

}

Catch (ArgumentException ex)

{

Console. WriteLine ("argumentNullException: {0}", ex );

}

Catch (SocketException exp)

{

Console. WriteLine ("SocketException: {0}", exp );

}

}

Send messages to the server

?

1

2

3

4

5

6

7

8

9

10

11

12

13

Private void button3_Click (object sender, EventArgs e)

{

If ("" = txt_target.Text)

{

MessageBox. Show ("No dialog character selected ");

Return;

}

// Send information to the server

String sendStr = txt_name.Text + "@" + target + ":" + txt_message.Text;

SendMessage (sendStr );

Rch_back.Text + = "\ n" + sendStr;

Txt_message.Text = "";

}

Stealth

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

Private void button2_Click (object sender, EventArgs e)

{

Try

{

SendMessage (">" + txt_name.Text );

// Cc. Disconnect (true );

// Cc. Shutdown (SocketShutdown. Both );

// Cc. Close ();

}

Catch (Exception exp)

{

CommonFunction. WriteLog (exp, exp. Message );

}

}

The above is all the content of this article. I hope you will like it.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.