Client Program:
1. Open vs.net and create a project with the C # template "Windows application". You may wish to name it "chatclient ".
2. layout interface. Add a ListBox control (used to display the user list), a RichTextBox Control (used to display chat messages and system messages), and a Textbox Control (used to send messages) to the interface ), a checkbox control (whether it is a whisper), a statusbar control, and four button controls ("connection", "Disconnect", "Start record", and "send "). For details about the attribute settings of each control, refer to the specific settings in the source code. The image after the interface is designed is as follows:
3. Write the code of the client program.
When the client tries to connect to the server, a connection must be established and must be registered with the server. The establishconnection () function uses a tcpclient to connect to the server, and creates a networkstream to send messages. In addition, the port number is the same as that on the server, both of which are 5555. The establishconnection () function is as follows:
Private void establishconnection ()
{
Statusbar1.text = "connecting to server ";
Try
{
Clientsocket = new tcpclient (serveraddress, SERVERPORT );
NS = clientsocket. getstream ();
Sr = new streamreader (NS );
Connected = true;
}
Catch (exception)
{
MessageBox. Show ("cannot connect to the server! "," Error ",
Messageboxbuttons. OK, messageboxicon. Exclamation );
Statusbar1.text = "disconnected ";
}
}
After the connection to the server is successful, the program uses the registerwithserver () function to send a conn command to the server. This command first sends the user name, and then obtains the list of all other users from the server. The list of all users is displayed in the ListBox control. This function is as follows:
Private void registerwithserver ()
{
Try
{
String command = "conn |" + chatout. text;
Byte [] outbytes = system. Text. encoding. ASCII. getbytes (command. tochararray ());
NS. Write (outbytes, 0, outbytes. Length );
String serverresponse = Sr. Readline ();
Serverresponse. Trim ();
String [] tokens = serverresponse. Split (New char [] {'| '});
If (tokens [0] = "list ")
{
Statusbar1.text = "connected ";
Btndisconnect. Enabled = true;
}
For (INT n = 1; n
Lbchatters. Items. Add (tokens [N]. Trim (New char [] {'/R','/N '}));
This. Text = clientname + ": connected to the server ";
}
Catch (exception)
{
MessageBox. Show ("an error occurred during registration! "," Error ",
Messageboxbuttons. OK, messageboxicon. Exclamation );
}
} |