Socket entry Notes use TcpClient to implement a simple chat room, sockettcpclient

Source: Internet
Author: User
Tags getstream

Socket entry Notes use TcpClient to implement a simple chat room, sockettcpclient
Effect

 

Implementation

Use TcpListener to create a server that receives messages sent from all clients, and then the server sends the messages to other clients.

The client uses TcpClient to send messages to the server, receive messages from the server, and directly interact with other clients.

Server receiving Client

Start a thread and receive the client through an endless loop. after receiving the message, put it in a collection and save it for message forwarding. each client starts another thread to receive messages sent from this client.

The method for receiving client AcceptTcpClient () is the blocking method. When the program exits and releases resources, an exception is thrown. You can use the Pending () method to determine whether a Pending link request exists, receive the request again. this avoids exceptions caused by exit.

It is received every 1 second.

/// <Summary> /// receiving client /// </summary> private void AcceptClient () {try {while (_ isAccept) {if (_ listener. pending () {TcpClient client = _ listener. acceptTcpClient (); IPEndPoint endpoint = client. client. remoteEndPoint as IPEndPoint; _ clients. add (endpoint. toString (), client); // Add to the front-end client list lbx_Clients.Dispatcher.Invoke () =>{ lbx_Clients.Items.Add (endpoint. toString () ;}); // The message receiving Thread reciveMessageThread = new Thread (ReciveMessage); reciveMessageThread. start (client);} else {Thread. sleep (1000) ;}} catch (Exception ex) {MessageBox. show (ex. message );}}
Receive and forward messages

It is also an infinite loop reception. Read () method is used to receive messages. If the remote host has closed the connection, Read () will immediately return zero bytes. In this case, the loop will jump out, release resources, and end the thread.

/// <Summary> /// receives the message // </summary> /// <param name = "obj"> TcpClient </param> private void ReciveMessage (object obj) {TcpClient client = obj as TcpClient; IPEndPoint endpoint = null; NetworkStream = null; try {endpoint = client. client. remoteEndPoint as IPEndPoint; stream = client. getStream (); while (true) {byte [] data = new byte [1024]; // If the remote host has closed the connection, Read immediately returns the zero-byte int length = stream. read (data, 0, data. length); if (length> 0) {# region if string msg = Encoding. UTF8.GetString (data, 0, length); // Add to the Front-End message list lbx_Messages.Dispatcher.Invoke () =>{ lbx_Messages.Items.Add (string. format ("{0 }:{ 1}", endpoint. toString (), msg) ;}); // send to other clients foreach (KeyValuePair <string, TcpClient> kvp in _ clients) {if (kvp. value! = Client) {string writeMsg = string. format ("{0 }:{ 1}", endpoint. toString (), msg); byte [] writeData = Encoding. UTF8.GetBytes (writeMsg); NetworkStream writeStream = kvp. value. getStream (); writeStream. write (writeData, 0, writeData. length) ;}# endregion} else {// The client disconnects and jumps out of the loop break;} catch (Exception ex) {// Read is the blocking method. When the client exits, it will cause an exception to release resources and end this thread} finally {// remove lbx_Clients.Dispatcher.Invoke () => {lbx_Clients.Items.Remove (endpoint. toString () ;}); // releases the resource stream. dispose (); _ clients. remove (endpoint. toString (); client. dispose ();}}
The client receives messages.

Enable the thread to receive messages sent by the server in an endless loop. If Read () returns 0, the server is disabled.

/// <Summary> /// receives the message // </summary> private void ReciveMessage () {try {NetworkStream stream = _ client. getStream (); while (true) {byte [] data = new byte [1024]; int length = stream. read (data, 0, data. length); if (length> 0) {string msg = Encoding. UTF8.GetString (data, 0, length); // Add to the frontend message list lbx_Messages.Dispatcher.Invoke () =>{ lbx_Messages.Items.Add (msg) ;});} else {MessageBox. show ("server closed"); stream. dispose (); break ;}} catch (Exception ex) {// Read is the method. If the program exits and releases resources, an Exception is thrown and the thread is not processed }}

Download source code:

Server: SocketServerDemo.zip

Client: SocketClientDemo.zip

Related Article

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.