Operate TCP/IP sockets in asynchronous mode -- implement simple chat rooms in asynchronous mode

Source: Internet
Author: User
Tags getstream

Common TCP/IP development methods should be very skillful, but problems often occur during system development.

For example, when developing a simple chat room, Windows ApplicationsProgramIt will run in synchronous mode. The more clients you listen to, the heavier the server load will be, and the message sending and receiving will be affected. At this time, we should try to use Asynchronous TCP/IP communication to relieve the pressure on the server.

 

The following uses the simplest example of a chat room server to describe the power of asynchronous TCP/IP. First, a chatclient class is developed as the client-managed proxy class. Whenever the server receives information, information processing is sent to every online customer.

Void Main ()
{

IPaddress = IPaddress. parse ("127.0.0.1" ); // Default address
Tcplistener
Tcplistener = new tcplistener (IPaddress, 500) );
Tcplistener. Start ();
While (Islisten)
// Implement listening in an endless loop
{
Chatclient =
New
Chatclient (tcplistener. accepttcpclient (); // call a chatclient object to implement listening

}
Tcplistener. Stop ();

}


There is a static hashtabel variable clients in the chatclient, which is used to store online client information. Every time a client is listened to, the system generates a chatclient object, add the client information to the clients variable. When receiving client information, the information will call the receive (iasyncresult async) method to send the received information to each online customer.

It is worth noting that the system uses stream whenever it receives customer information. the beginread () method receives information and sends the information to each online customer. In this way, the information can be received asynchronously, so that the main thread can be released as soon as possible, improve system performance.

Public
Class chatclient

{

Private
Tcpclient _ tcpclient;
Private byte[] Bytemessage;
Private string
_ Clientendpoint;

Public
Volatile string
Message;
Public static hashtable clients = new
Hashtable (); // multiple client addresses stored in this static variable


Public
Chatclient (tcpclient)
{
_ Tcpclient
=
Tcpclient;
_ Clientendpoint =
_ Tcpclient. Client. remoteendpoint. tostring ();
Console. wrtieline ("connection succeeded, client endpoint is" + _ clientendpoint );


Chatclient. Clients. Add (_ clientendpoint, this );
// Each time an object is created, the chatclient object of the client is saved to clients;

Bytemessage = new
Byte[_ Tcpclient. receivebuffersize];


Lock (_ tcpclient. getstream () // receives information. Use lock to avoid data conflict.

{


_ Tcpclient. getstream (). beginread (bytemessage, 0, _ tcpclient. receivebuffersize,
New asynccallback (receive), null );


// Use an asynchronous Io thread to read data, so that each client is processed in an IO thread, so that the main thread is released as soon as possible.

// This reduces the pressure on the server.

}
}

Public voidReceive (iasyncresult)

{
Try
{
Int Length;


Lock (_ Tcpclient. getstream ())
// Receive information and use lock to avoid data conflict
{

Length =
_ Tcpclient. getstream (). endread (iasyncresult );

}
If (length <1 )
{

MessageBox. Show (_ tcpclient. Client. remoteendpoint + "disconnected" );

Clients. Remove (_ tcpclient );
Return ;

}


Message = encoding. Unicode. getstring (bytemessage, 0, Length );
Sendtoeveryone (Message );


// At this time, we can call the sendtoeveryone method here and use the clients variable to send information to each client using the stream. Write method.



Lock
(_ Tcpclient. getstream () // listen again and use lock to avoid data conflict

{
_ Tcpclient. getstream (). beginread (bytemessage, 0,
_ Tcpclient. receivebuffersize, new asynccallback (receive), null);


// call stream again. beginread method to listen to the following Customer Information
}< br> catch (Exception ex)
{

Clients. Remove (_ tcpclient );

_ Tcpclient. getstream (). Close ();

_ Tcpclient. Close ();
}
}

 

// Convert the information into binary data using the send method and then send it to the client

Public void send (string message)
{
Try
{
Networkstream ns;
Lock (_ tcpclient. getstream ())
{
NS = _ tcpclient. getstream ();
}
Byte [] bytemessage = encoding. ASCII. getbytes (Message );
NS. Write (bytemessage, 0, bytemessage. Length );
NS. Flush ();
}
Catch (exception ex)
{
MessageBox. Show (ex. Message );
}
}

// Because the client information is recorded in the hashtabel variable clients, when the information is received, the information is sent to each online customer through this variable.

Public void sendtoeveryone (string message)
{
Foreach (dictionaryentry client in clients)
{
Chatclient = (chatclient) client. value;
Chatclient. Send (Message );
}
}

}

Test results:

The window design and client design are omitted here. The purpose here is to understand the principle of receiving multi-thread TCP/IP information on the server.

In this example, the chatclient class uses an asynchronous Io thread to read data, so that each client is processed in an IO thread, so that the main thread is released as soon as possible,This reduces the pressure on the server.

At this time, you can perform a test. By default, this chat room can accept connections from about 3000 clients and still work properly.

 

 

. Net Basics

Operate TCP/IP sockets in asynchronous mode -- implement simple chat rooms in asynchronous mode Use the ". Net Extension Method" to simplifyCode(Example: Evaluate null values and use the extended method to implement the LINQ operator foreach) Division class and division method The mysteries of reflection Update an object Using Generics and reflection (ADO. NET Entity Framework)

 

Author: wind dust prodigal son
Http://www.cnblogs.com/leslies2/archive/2011/01/27/1935860.html

Original Works. Indicate the author and source when reprinting.

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.