Introduction

I've been working with sockets since 2000, using Delphi 5.0 and some third-party libraries (Synapse). My very first socket application just copied files between many clients and one server. The client app checks a folder to see if files exist, asks the server where to copy the files in the network and, after copying the files, flags the database record indicating that a file has been moved. The server listens to the client connections, and both exchange XML messages indicating the state of each file copy. Synapse is a blocking socket implementation, and I needed a thread pooling mechanism that works like an HTTP server, because I couldn't keep the connection open (one thread per connection). My solution was to use some IOCP functions to pool the client requests (code) and close the connection after the message exchange was terminated.

Now, using C#, I decided to write a socket server and client library that helps me to only have to think about the message exchange (the process) and let .NET do the hard job. So, I needed the following features:

Asynchronous processing

Some encryption and compression capabilities

Encapsulate the socket, and encrypt the services in the interfaces and separate them from the host implementation

Socket Connection

The ISocketConnection is the base interface for the socket connections, and describes all the connection properties and the methods. The ConnectionID property defines a unique connection ID using a GUID string. The CustomData property defines a custom object that can be associated with the connection. The Header property is the socket service header used in each message that is encapsulated in a packet message. Only messages with a defined header will be accepted. The LocalEndPoint and RemoteEndPoint are the socket IP end points used in the connection. SocketHandle is the socket handle given by the OS.

The IClientSocketConnection and IServerSocketConnection inherit the ISocketConnection, and each one has special functions. The IClientSocketConnection can reconnect to the server using the BeginReconnect method, and the IServerSocketConnection can communicate with other connections in the server host using the BeginSendTo and BeginSendToAll methods, and can get the ConnectionId using the GetConnectionById method. Every connection knows the host, the encryption, the compression type, and can send, receive, and disconnect itself from the other part. This interface is used in the ISocketService interface to allow the user to interact with socket connections.

Internally, in the library implementation, all the connection interfaces are created using the base connection implementations: BaseSocketConnection, ClientSocketConnection, and ServerSocketConnection.

Socket Service

The ISocketService describes the connection events. These events are fired by the host, and have a ConnectionEventArgs argument which has an ISocketConnection that identifies the connection. In the OnReceived and OnSent events, a MessageEventArgs is passed, which has the sent or received array of bytes. In the OnDisconnected event, a DisconnectedEventArgs is passed; the Exception property indicates if the disconnection has been caused by an exception.

The ISocketService implementation can be done in the same host assembly, or another assembly referenced by the host. This allows the user to separate the host implementation from the socket service, helping the administration in a server or a domain.

Connection Host

With the ISocketService created, you need to host the service and the service connections. Both the server and the client host have the same parent class, BaseSocketConnectionHost, which keeps a list of connections, encrypts and compresses the data buffers, enqueues the service requests and ensures that all data buffer has been sent or received, checks messages headers, and checks for idle connections. The CheckTimeoutTimer, periodically, at IdleCheckInterval, checks if the connections become idle, using the IdleTimeOutValue as the idle timeout. Header is the socket service header used by the host. HostType indicates if a host is a server or a client host. SocketBufferSize defines the size of the socket send and receive buffer. SocketService is the instance of ISocketService that drives the message exchange between the connections.

Encrypt and Compress

Every time you send and receive messages, the host checks if the data must be encrypted and/or compressed, and this work is made by the CryptUtils static class. The CreateSymmetricAlgoritm creates an ISymmetricAlgoritm based on the encryptType parameter. The DecryptData and DecryptDataForAuthenticate are used, respectively, to decrypt the received message and check the hash sign on the authenticate procedure. The EncryptData and EncryptDataForAuthenticate, respectively, encrypt the data to be sent and sign the authenticated message.

The encrypted data buffer is labelled with the service header and the data buffer length, becoming a packet buffer. This packet buffer is controlled by the MessageBuffer class that keeps information about the packet buffer offset, length, the remaining bytes, and the raw buffer.

Enqueuing requests

Every time you call BeginReceive or BeginSend in ISocketService, the host checks if some request has been initiated. If a request is in process, the host enqueues the request. If not, it fires the request.

Ensure send and receive

To ensure that all data buffer is sent, the BaseSocketConnectionHost checks the bytes sent, and compares it to the MessageBuffer class. It continues to send the remaining bytes till all the data buffer is sent:

The same approach is used in the receive data buffers because, to read data, a MessageBuffer is used as the read buffer. When the receive callback is called, it continues to read till all the bytes in the message are read:

Check message header

If the socket service uses some header, all the send and receive processes need to create a packet message indicating the header and the message length. This packet label is created using the following structure:

The first label's part is the socket service header. The header is an array of bytes of any length, and you need some advice here: if you choose a very small header, maybe you can have a message with the same array of bytes somewhere, and the host will lose the sequence. If you choose a very long array of bytes, the host can spend the processor's time to verify if the message header is equal to the socket service. The second part is the packet message length. This length is calculated adding the raw message data buffer length, encrypted and/or compressed, plus the header length.

Sending packets

As said before, every time you send messages, the host checks if the data must be encrypted and/or compressed, and, if you choose to use some header, the raw buffer is controlled by the MessageBuffer class. This class is created using the GetPacketMessagestatic method:

Receiving packets

The receive process, if you're using some socket service header, needs to check the header, and continues to read bytes till all the packet message is received. This process is executed in the read callback:

The read callback method first checks if the connection has some header and, if not, just gets the raw buffer and continues. If the connection has some header, the method needs to check the message header against the socket service header. Before doing that, it checks if the packet message length is greater than the connection header length, to ensure that it can parse the total message length. If not, it reads some bytes. After checking the header, the method parses the message length, and checks with the packet length. If the length is equal, it gets the raw buffer and terminates the loop. If the message length is less than that of the packet message, we have the message plus some data. So, the method gets the raw buffer and continues to read using the same MessageBuffer class. If the length of the message is greater than that of the packet message, before reading some data, it just resizes the packet buffer to the message size, ensuring enough room for more read bytes.

Checking idle connections

Using the BeginSend and BeginReceive methods of ISocketConnection doesn't return some IAsyncResult to know if the method was completed or not allowing disconnection after some timeout value. To prevent this, the BaseSocketConnectionHost has a System.Threading.Timer that periodically checks the LastAction property of BaseSocketConnection. If LastAction is greater than the idle timeout, the connection is closed.

Crypto Service

The ICryptoService describes the authentication methods fired when the connection is made to the other part. The OnSymmetricAuthenticate method is fired when EncryptType.etRijndael or EncryptType.etTripleDES is used, and OnSSLXXXXAuthentication is fired when EncryptType.etSSL is used. Like ISocketService, the ICryptService can be done in the same host assembly, or another assembly referenced by the host, so you can have one ICryptoService implementation used in many ISocketService implementations.

SSL authentication

There's a new stream class called SslStream in .NET 2.0 which can authenticate SSL streams. The SslStream's constructor accepts a NetworkStream class, and this stream is created using the Socket class. So, using SslStream, you can send and receive data buffers using socket connections.

Server authentication

The SslStream authentication is done in both the client and the server, but each one has different parameters. In the server side, you need to pass a certificate using the X509Certificate2 class, either finding in the certificate store using X509Store, or by creating it from a certification file (.cer). Also, you can request a client authentication and check the certificate's revocation. The following code is an example of an SSL server authentication using ICryptService:

Client authentication

On the client side of the SSL authentication, you need to pass the host name of the server certificate, and if this name doesn't match, the authentication fails. You can pass a client certificate collection using X509Certificate2Collection. If the server doesn't request a client authentication, you don't need to pass the collection but, if the server requests it, you can find the certificates using X509Store. You can also request a client certificate's revocation. This is an example of SSL client authentication in ICryptoService:

Certificates

To create certificates, you can use the MakeCert.exe tool found in .NET, and there's a lot of information available about it. You can take a look at John Howard's page, this MS post, and this website.

Symmetric authentication

To implement some symmetric encryption and authentication in this library, I decided to put a post in Microsoft newsgroups. Unfortunately, for the post, but luckily for the knowledge sharing (many thanks to Joe Kaplan, Dominick Baier, and Valery Pryamikov), I decided to use William Stacey's implementation example "A generic method to send secure messages using an exchanged session key". In this code, the symmetric key used in the session is encrypted and signed using RSA key pairs, and the client part needs to know the encrypted server's public key, meaning that this key isn't received from the server in the authentication process. Both the client and the server need to know this key through a manual process. To ensure this, the OnSymmetricAuthenticate needs a RSACryptoServiceProvider class providing the key pair for encryption. You can fill the RSACryptoServiceProvider from an XML string, a file, a CspParameters class, or a certificate. Here is an example of symmetric authentication:

The authentication message

The symmetric authentication uses the AuthMessage structure to exchange session keys between the client and the server. The SessionKey and SessionIV properties are, respectively, the symmetric key and the initialization vector of the algorithm. The Sign property is the hash code generated by the client using the sign RSACryptoServiceProvider class created internally, and its public key is exchanged using the SourceKey property. This internal sign key pair is necessary to sign the AuthMessage, and the server can ensure that the AuthMessage is accurate. This process is done using the following code:

On the client side of the symmetric authentication, the OnSymmetricAuthenticate is called, getting the RSACryptoServiceProvider to encrypt the session key generated by the CryptUtils.CreateSymmetricAlgoritm method. The AuthMessage is filled with the encrypted session key, session IV, and the sign public key. To sign the message, the SourceKey, SessionKey, and signMessage are used, and the resulting hash is assigned to the Sign property.

On the server side of the symmetric authentication, a MessageBuffer is used to receive the socket buffer. The read callback method continues to read till a completed AuthMessage is received. With this message, the method calls the OnSymmetricAuthenticate to get the RSACryptoServiceProvider to decrypt the session key, session IV, and the sign public key. With all the keys decrypted, the method verifies the Sign property to ensure that the AuthMessage is accurate, using the SourceKey, SessionKey, and signMessage.

Connection Creator

Although BaseSocketConnectionHost can manage ISocketConnection connections, it cannot create them. This job is made by BaseSocketConnectionCreator which creates and initializes ISocketConnections. The CompressionType and EncryptType properties define, respectively, the compression and the encryption types that will be used in the connection. The CryptoService defines the ICrytoService instance used to initialize the connection, if needed. The Host property defines the host of the BaseSocketConnectionCreator; it can be a server or a client host. The LocalEndPoint defines the socket IP end point used in the connection, and it can have different behavior depending on the type of the creator.

SocketServer and SocketListener

The SocketServer and SocketListener are the classes needed to create a socket server. SocketServer is derived from BaseSocketConnectionHost, and manages ISocketConnections. The SocketListener is derived from BaseSocketConnectionCreator, and listens for incoming connections, accepts a connection, and creates a new ISocketConnection to be used. A SocketServer can have as many SocketListeners attached as required, each one assigned to a local port to listen.

SocketServer constructor and methods

In the SocketServer constructor, the socketService parameter defines the ISocketService instance used by the server. The header parameters define the array of bytes used in the message header exchange. The socketBufferSize adjusts the socket buffer size. The messageBufferSize defines the maximum message size of the service. The idleCheckInterval indicates the interval for idle connections checking, in milliseconds. The idleTimeoutValue defines the timeout, in milliseconds, to be compared to each connection LastAction property.

To add SocketListener items in SocketServer, the method AddListener must be used. The localEndPoint parameter defines the local socket IP endpoint used to listen to connections. The encryptType and compressionType defines, respectively, the encryption and compression methods used in the new accepted connection. The cryptoService defines the ICryptoService used to authenticate the encryption method chosen. The backLog limits the listen queue of the OS socket to the defined number, and acceptThreads sets the calling number of the socket's BeginAccept to increase the accepted performance.

HostThreadPool

This library uses asynchronous socket communication which, in turn, uses the .NET ThreadPool. In the .NET 2.0 ThreadPool, the thread number can be controlled using the SetMaxThreads and SetMinThreads methods, and I think there are a lot of improvements in this class. But, if you don't want to use the .NET class, you can use a managed thread pool called HostThreadPool, very similar to Stephen Toub's ManagedThreadPool. HostThreadPool uses a list of managed threads that keeps increasing as more enqueueing tasks are provided. To use this class instead of the .NET ThreadPool in SocketServer, just set the minThreads and maxThreads constructor parameters to non-zero numbers.

SocketClient and SocketConnector

The SocketClient and SocketConnector are the classes needed to create a socket client. SocketClient is derived from BaseSocketConnectionHost and, like SocketServer, manages ISocketConnections. The SocketConnector is derived from BaseSocketConnectionCreator, and it connects with the socket server and creates a new ISocketConnection to be used. A SocketClient can have as many SocketConnectors attached as required, each one connecting to a socket server, and they can be assigned to a local address and a local port to start the connection.

SocketClient constructor and methods

The SocketClient constructor has the same parameter signature as the SocketServer class. To add SocketConnector items in SocketClient, the method AddConnector must be used. The remoteEndPoint parameter defines the remote socket IP endpoint used for the connection. The encryptType and compressionType define, respectively, the encryption and compression methods used in the new connection. The cryptoService defines the ICryptoService used to authenticate the encrypted method chosen. The reconnectAttempts and reconnectAttemptInterval define, respectively, the number of reconnect attempts when using BeginReconnect method and the time interval to reconnect. The localEndPoint defines the local socket IP endpoint used to start the connection process to the remote endpoint.

Echo demo project

There's an Echo demo project available in the article download file, using Console, Windows Forms, and Windows Service hosts and clients, and all them use the same EchoSocketService and EchoCryptService. The demos are divided by their type as follows:

Hosts

Console

EchoConsoleClient

EchoConsoleServer

Windows Forms

EchoFormClient

EchoFormServer

Echo<code>Form </code />(Forms template)

Windows Service

EchoWindowsServiceServer

Services

EchoSocketService

EchoCryptService

Conclusion

There's a lot going on here, and I think this library can help anyone who wants to write asynchronous sockets with encryption and compression. Any comments will be appreciated.

History

May 15, 2006: Initial version

May 19, 2006: Some English text corrections (sorry, I'm still learning!), and rechecking the demo sources

June 06, 2006: Version 1.2 with the following changes:

Minor bugs fixed

All "Sended" changed to "Sent" (thanks vmihalj)

ReadCanEnqueue now works correctly and with HostThreadPool (thanks PunCha)

Added reconnectAttempts and reconnectAttemptInterval to allow client connection reconnects as many times as is needed in a timed interval (thanks Tobias Hertkorn)

April 01, 2007: Version 1.3 with the following changes:

Fixed rawbuffer = null

Fixed BeginAcceptCallback: stops accepting if exception occurs

Fixed BeginSendCallback: PacketRemaining bytes should be used

Socket config section added in demos

New message size (64K)

HosThreadPool removed

Header changed to Delimiter property with new delimiter options:

dtNone: No message delimiter

dtPacketHeader: Version 1.2 backward

dtMessageTailExcludeOnReceive: Use custom delimiter at end of message (Exclude delimiter on receiving)

dtMessageTailIncludeOnReceive: Use custom delimiter at end of message (Include delimiter on receiving)

Comments and Discussions

I'm getting System.InvalidOperationException while disconnecting the socket connection from server stating that An asynchronous socket operation is already in progress using this SocketAsyncEventArgs instance. Please someone help me in this regard...Thanks.

I am using your excellent socket extension in another open source project called "YAT - Yet Another Terminal" (https://sourceforge.net/projects/y-a-terminal/). YAT features an RS-232/422/423/485 terminal optimized for communication with embedded systems. In addition it also supports TCP client/server/AutoSocket and UDP connections for PC based embedded systems simulations, AutoSocket being an automatic client/server detection mechanism.

At first I was using ALAZ 1.4/1.5 on .NET 2.0, then updated to ALAZ 2.0 and .NET 3.5. After the update it didn't build right from start. But then I realized that back in 2007 I made significant modifications to ALAZ:
- Adding support for UDP (HostType.htUdp)
- Improving stability by adding exception handling at several places
- Changing SocketsEx\BaseSocketConnectionHost.StopConnections() from blocking to non-blocking
- Some other modification which in retrospect where rather silly

I was glad to see that you have improved the exception handling in ALAZ 2.0. So I didn't need to redo these modifications. But I had to redo the support for UDP. Isn't a big thing, still, I am wondering whether you could consider to add UDP support to the original ALAZ library for future versions. In retrospect, I should have given you this input already in 2007, my fault. Better later than never

SocketsEx\BaseSocketConnectionHost.StopConnections()
I am not exactly getting why this method is blocking and therefore makes Stop() blocking. The Start() method isn't blocking.
If Stop() is called from a GUI thread and the GUI is attached to the Disconnected event, a dead-lock happens:
- The GUI thread is blocked here
- FireOnDisconnected is blocked when trying to synchronize Invoke() onto the GUI thread

Disposal
Probably due to the modifications mentioned above, tt seems that TCP server sockets don't properly shut down when Dispose() is called. As I understand the purpose of Dispose(), a call to this method must always be possible and it must immediately release all resources the object holds. In case of TCP server this seems not the case.

Distribution
There are a few files in your distribution which I think shouldn't be in there. I had to remove/untick them before checking them into my SVN.
- *.user
- \Code\Demos\Echo\EchoConsoleServer\Service References
- \Code\Demos\Echo\EchoFormServer\*.tmp
- \Code\Source\ALAZ.SystemEx\bin\
- \Code\Source\ALAZ.SystemEx.NetEx\bin\

Some other inputs
- ALAZ AssemblyInfo.cs should have [assembly: CLSCompliant(true)] enabled
> Allows libraries/programs to be CLS compliant
- The "ALAZLibSN.snk" should be within "\Properties"
- The "ALAZLibSN.snk" should be available in both projects
- The "ALAZLibSN.snk" should be referenced/enabled in both projects
- How about adding a static class diagram to the Visual Studio project?
- How about providing BaseSocketConnectionHost/SocketClient/SocketServer constructors that use ctWorkerThread by default?
- How about using System.Threading.Timeout.Infinite to emphasize infinite timeout values?
- How about providing default constants for 1024 * 2 and 1024 * 16?

I came across another issue when shutting down a pair of an ALAZ client connected to an ALAZ server within the same application. I ran into a deadlock while shutting down the open connection. It happens in ALAZ.SystemEx.NetEx.SocketsEx.BaseSocketConnection.Active.get(). Is there a need to lock the field when reading its status? The situation is as follows:
Thread A) at ALAZ.SystemEx.NetEx.SocketsEx.BaseSocketConnectionHost.BeginReadCallbackAsyncP trying to call connection.BeginDisconnect()
> ALAZ.SystemEx.NetEx.dll!ALAZ.SystemEx.NetEx.SocketsEx.BaseSocketConnection.Active.get() Line 286
> ALAZ.SystemEx.NetEx.dll!ALAZ.SystemEx.NetEx.SocketsEx.BaseSocketConnectionHost.FireOnException(ALAZ.SystemEx.NetEx.SocketsEx.BaseSocketConnection connection =
{ALAZ.SystemEx.NetEx.SocketsEx.ClientSocketConnection}, System.Exception ex = {Cannot evaluate expression because the current thread is in a sleep, wait, or join}) Line 551
> ALAZ.SystemEx.NetEx.dll!ALAZ.SystemEx.NetEx.SocketsEx.BaseSocketConnectionHost.BeginDisconnect(ALAZ.SystemEx.NetEx.SocketsEx.BaseSocketConnection connection =
{ALAZ.SystemEx.NetEx.SocketsEx.ClientSocketConnection}) Line 1453
> ALAZ.SystemEx.NetEx.dll!ALAZ.SystemEx.NetEx.SocketsEx.BaseSocketConnection.BeginDisconnect() Line 558
> ALAZ.SystemEx.NetEx.dll!ALAZ.SystemEx.NetEx.SocketsEx.BaseSocketConnectionHost.BeginReadCallbackAsyncP(object state = {System.Net.Sockets.SocketAsyncEventArgs}) Line 1161
Thread B) at ALAZ.SystemEx.NetEx.SocketsEx.BaseSocketConnectionHost.BeginReadCallbackAsyncP trying to get the connection state
> ALAZ.SystemEx.NetEx.dll!ALAZ.SystemEx.NetEx.SocketsEx.BaseSocketConnection.Active.get() Line 286
> ALAZ.SystemEx.NetEx.dll!ALAZ.SystemEx.NetEx.SocketsEx.BaseSocketConnectionHost.BeginReadCallbackAsyncP(object state = {System.Net.Sockets.SocketAsyncEventArgs}) Line 1146
The Main Thread at ALAZ.SystemEx.NetEx.SocketsEx.SocketServer.Stop()
> ALAZ.SystemEx.NetEx.dll!ALAZ.SystemEx.NetEx.SocketsEx.BaseSocketConnection.Active.get() Line 286
> ALAZ.SystemEx.NetEx.dll!ALAZ.SystemEx.NetEx.SocketsEx.BaseSocketConnectionHost.BeginDisconnect(ALAZ.SystemEx.NetEx.SocketsEx.BaseSocketConnection connection =
{ALAZ.SystemEx.NetEx.SocketsEx.ServerSocketConnection}) Line 1435
> ALAZ.SystemEx.NetEx.dll!ALAZ.SystemEx.NetEx.SocketsEx.BaseSocketConnection.BeginDisconnect() Line 558
> ALAZ.SystemEx.NetEx.dll!ALAZ.SystemEx.NetEx.SocketsEx.BaseSocketConnectionHost.StopConnections() Line 340
> ALAZ.SystemEx.NetEx.dll!ALAZ.SystemEx.NetEx.SocketsEx.SocketServer.Stop() Line 207

Also, there seems to be a null reference issue in ALAZ.SystemEx.NetEx.SocketsEx.BaseSocketConnectionHost.StopCreators() on line 311 (FWaitCreatorsDisposing.WaitOne). I added a try-catch around the statement.

Another issue I found in SocketListener.BeginAcceptCallback on line #229 AcceptAsync(e2):

An unhandled System.ObjectDisposedException was thrown while executing this test : The SafeHandle has been closed.

This issue occured while performing endurance tests using YAT AutoSockets.

And the last issue for today, found in BaseSocketConnection.Active:

I get another deadlock because I have to synchronize events onto my main/GUI thread. In case of having an application with two sockets connected to each other I get a deadlock upon shut down. Thus I have removed the lock in the get{} property of BaseSocketConnection.Active.

UDP
I have removed all UDP stuff and use System.Net.Sockets.UdpClient directly

Now, are you still developing ALAZ? Or has this project, as so many others, come to a dead-end?

The purpose of this library is show how Sockets can be development on .Net; it cannot be called a "project" with upgrades/new versions. Maybe I'll write some update using .Net 4.5 but, till there, you can check SuperSocket Library hosted on codeplex.

Thanks for the hint. Over the last couple of days I indeed evaluated SuperSocket, among some other libraries as show n below.

However, I found that SuperSocket doesn't really suit the needs of YAT. SuperSocket is designed to be used for higher level applications, such as custom protocols on TCP/IP. YAT doesn't deal with protocols, it just requires a socket library on binary stream level, but more convenient then what System.Net.Sockets provides by default.

ich found out that the library gives the server no way to check the client certificate - it just checks for signed or not. so if a client sends a valid and signed certificate back to server it will pass the test - whether its right or wrong.

i simply use the same ValidateServerCertificate for that - server side.

First of all a huge thank you for writing the article and the library. The code is clean and concise, I learned a great deal from it and it really cleared up the subject on quite a few things for me. I've looked around for a similar library and yours is hands down the best one around.

I am implementing a message oriented layer on top of TCP that should conform to an event based interface almost identical to NetEx's. I am thinking about reusing your robust and tested code rather than reinventing the wheel but have noticed the header option had been removed some time ago. Spec for my library requires a two byte message length header (a prefix) and since your library seems mature I wouldn't want to mess it up with a quick and dirty "fix".

I would like to have your opinion on whether this is a trivial change or a more serious redesign would be required. I'd appreciate any pointers you are willing to offer.

Dear Andre,
I'm writing to ask your advice whether yourself, or someone you may recommend, might be able to help us sort out a problem we have come across in trying to write a web-server that receives asyncronous data from a number of GPRS telemetry transmitters.
I will first admit that I am not a web programmer, and have fairly limited programming experience, but we have been working with another programmer who has written a php based webserver, but it's getting stuck on the TCP hold issue. And that is once a telemetry sender has connected its socket with the web server socket, communications with other telemetry units is locked out. So we can only handle one socket connection at a time. Whereas we need to be able to receive connections and data from several sources simultaneously, or randomly, as they are all transmitting their data without any orchestration between them or the server.

As I read your excellent article on asyncronous socket programming, it seems that that sort of capability is what we need to address this problem.
Could you please advise if you might be able to help us?
With thanks,
Glen Johnston
Canberra, Australia.

Exception System.Security.Cryptography.CryptographicException: Object identifier (OID) is unknown.
-
Worked well under testing environment. However, this is the error I got when I put it on to a windows 2003 x64 server.
Is there a fix to it? Anyone happen to know how? Please help!!!

great work by you~
i got a problem running the demo chatclient and chatserver,it seemed that when i runned the server and client on the same computer,the server couldn't hold a connection for the fifth client !i mean the connection won't last long ,it disconnected the moment it connected the server,i didn't event had a chance to send message.but the preceded four connections worked well,i don't why.

So obviously, the problem is that the MessageBufferSize in both the server and client are too small at 512 bytes. The message buffer includes a list of the connected users (to display in the user list panel of the client) in some instances, so once you include a 5th user, the buffer size requires more than 512 bytes.

You can fix this by increasing the MessageBufferSize in both the client and server. In my tests, setting it to 1024 allowed me to connect over 20 clients without issues. Note though that as the number of users and/or length of nicknames increases, the size requirement will increase.