The main part of the program should be the serviceclient () function. This function is an independent thread, and its main part is a while loop. In the loop body, the program processes various client commands. The server receives the string from the client in ASCII code, which contains a separator in the form of "|. The previous part of the string "|" is a specific command, including the conn, chat, priv, and gone types. The conn command establishes a new client connection, sends the existing user list to the new user, and notifies other users that a new user is added. The chat Command sends new information to all users. The priv Command sends a private message to a user. The gone command removes an existing user from the user list and notifies other users that the user has left. At the same time, the gone command can set the Boolean variable keepalive to false to end the thread connected to the client. The serviceclient () function is as follows:
Private void serviceclient ()
{
Socket Client = clientsocket;
Bool keepalive = true;
While (keepalive)
{
Byte [] buffer = new byte [1024];
Client. Receive (buffer );
String clientcommand = system. Text. encoding. ASCII. getstring (buffer );
String [] tokens = clientcommand. Split (New char [] {'| '});
Console. writeline (clientcommand );
If (tokens [0] = "conn ")
{
For (INT n = 0; n
{
Client Cl = (client) clients [N];
Sendtoclient (CL, "Join |" + tokens [1]);
}
Endpoint Ep = client. remoteendpoint;
Client c = new client (tokens [1], EP, clientservice, client );
Clients. Add (C );
String message = "list |" + getchatterlist () + "/R/N ";
Sendtoclient (C, message );
Lbclients. Items. Add (C );
}
If (tokens [0] = "chat ")
{
For (INT n = 0; n
{
Client Cl = (client) clients [N];
Sendtoclient (CL, clientcommand );
}
}
If (tokens [0] = "priv ")
{
String destclient = tokens [3];
For (INT n = 0; n
{
Client Cl = (client) clients [N];
If (Cl. Name. compareto (tokens [3]) = 0)
Sendtoclient (CL, clientcommand );
If (Cl. Name. compareto (tokens [1]) = 0)
Sendtoclient (CL, clientcommand );
}
}
If (tokens [0] = "gone ")
{
Int remove = 0;
Bool found = false;
Int c = clients. count;
For (INT n = 0; n
{
Client Cl = (client) clients [N];
Sendtoclient (CL, clientcommand );
If (Cl. Name. compareto (tokens [1]) = 0)
{
Remove = N;
Found = true;
Lbclients. Items. Remove (CL );
}
}
If (found)
Clients. removeat (remove );
Client. Close ();
Keepalive = false;
}
}
}
In this way, the server-side program is basically complete. (For the code for other requests, see the form1.cs file in the source code.) The program running illustration is as follows: |