1. Programs are divided into servers and clients;
2. Any customer can communicate with the server;
3. The server can promptly display the status of connected clients and then notify all clients;
4. After the connection between the client and the server is successful, you can chat with any other user;
5. If the customer exits the program, the server will notify other customers.
I. server design and programming.
The server design interface is as follows:
The server code is as follows:
Using system; using system. collections. generic; using system. componentmodel; using system. data; using system. drawing; using system. LINQ; using system. text; using system. windows. forms; // Add the namespace using system. net; using system. net. sockets; using system. io; using system. threading; namespace windowsformsapplication1 {public partial class mainform: FORM {// The user private list used to save the connection <user> userlist = new list <user> (); // Use the local IP address IPaddress localaddress; // define the port number private const int Port = 51888 on the computer; private tcplistener mylistener; // define a flag, used to determine whether to exit normally all accept threads bool isnormalexit = false; // initialize public mainform () {initializecomponent (); listboxstatus when loading the main form. horizontalscrollbar = true; IPaddress [] addrip = DNS. gethostaddresses (DNS. gethostname (); localaddress = addrip [0]; buttonstop. enabled = false;} // click the listening button to process the event PRI Vate void buttonstart_click (Object sender, eventargs e) {mylistener = new tcplistener (localaddress, Port); mylistener. start (); additemtolistbox (string. format ("starting at {0 }:{ 1} listening to customer connections", localaddress, Port )); // create a thread to listen to the Client Connection Request thread mythread = new thread (listenclientconnect); mythread. start (); buttonstart. enabled = false; buttonstop. enabled = true;} // receive client connection private void listenclientconnect () {tcpclie NT newclient = NULL; while (true) {try {newclient = mylistener. accepttcpclient ();} catch {// when you click "Stop listening" or exit this form, accepttcpclient () will generate an exception, so use this exception to exit the loop break ;} user user = new user (newclient); thread threadreceive = new thread (receivedata); threadreceive. start (User); userlist. add (User); additemtolistbox (string. format ("[{0}] Enter", newclient. client. remoteendpoint); additemtolistbox (string. format ("Current connected user Number: {0} ", userlist. count) ;}} private void receivedata (Object userstate) {user = (User) userstate; tcpclient client = user. client; while (isnormalexit = false) {string receivestring = NULL; try {// read the string from the network stream. This method automatically determines the string length prefix receivestring = user.br. readstring ();} catch {If (isnormalexit = false) {additemtolistbox (string. format ("lost contact with [{0}], ended receiving user information", client. client. remoteendpoint); REM Oveuser (User);} break;} additemtolistbox (string. format ("from [{0}]: {1}", user. client. client. remoteendpoint, receivestring); string [] splitstring = receivestring. split (','); Switch (splitstring [0]) {Case "login": user. username = splitstring [1]; sendtoallclient (user, receivestring); break; Case "logout": sendtoallclient (user, receivestring); removeuser (User); return; Case "talk ": string talkstring = Receivestring. substring (splitstring [0]. length + splitstring [1]. length + 2); additemtolistbox (string. format ("{0} to {1}: {2}", user. username, splitstring [1], talkstring); sendtoclient (user, "talk," + User. username + "," + talkstring); foreach (User target in userlist) {If (target. username = splitstring [1] & user. username! = Splitstring [1]) {sendtoclient (target, "talk," + User. username + "," + talkstring); break ;}} break; default: additemtolistbox ("What do you mean:" + receivestring); break ;}}} private void sendtoclient (User user, string message) {try {// write the string to the network stream. This method automatically appends the string length prefix user. BW. write (Message); User. BW. flush (); additemtolistbox (string. format ("sent to [{0}]: {1}", user. username, message);} catch {additemtolistbox (S Tring. format ("failed to send information to [{0}]", user. username) ;}}// send the message to all customers. The name specifies the user to which the message is sent, and the content of the message is private void sendtoallclient (User user, string message) {string command = message. split (',') [0]. tolower (); If (command = "login") {for (INT I = 0; I <userlist. count; I ++) {sendtoclient (userlist [I], message); If (userlist [I]. username! = User. username) {sendtoclient (user, "login," + userlist [I]. username) ;}} else if (command = "logout") {for (INT I = 0; I <userlist. count; I ++) {If (userlist [I]. username! = User. username) {sendtoclient (userlist [I], message) ;}}}// remove a user. User indicates the user private void removeuser (User user) {userlist to be deleted. remove (User); User. close (); additemtolistbox (string. format ("current number of connected users: {0}", userlist. count);} private delegate void additemtolistboxdelegate (string Str); // to append status information in ListBox, STR stores the information to append private void additemtolistbox (string Str) {If (listboxstatus. invokerequired) {addite Mtolistboxdelegate d = additemtolistbox; listboxstatus. invoke (D, STR);} else {listboxstatus. items. add (STR); listboxstatus. selectedindex = listboxstatus. items. count-1; listboxstatus. clearselected () ;}}// press the private void buttonstop_click (Object sender, eventargs e) {additemtolistbox ("start to stop the service, and the user exits in turn! "); Isnormalexit = true; For (INT I = userlist. count-1; I> = 0; I --) {removeuser (userlist [I]);} mylistener. stop (); buttonstart. enabled = true; buttonstop. enabled = false;} // event private void mainform_formclosing (Object sender, formclosingeventargs e) triggered when the window is closed {If (mylistener! = NULL) {// trigger the buttonstop Click Event buttonstop. Too mclick ();}}}}
2. Client design and programming.
The client design interface is as follows:
The client code is as follows:
Using system; using system. collections. generic; using system. componentmodel; using system. data; using system. drawing; using system. LINQ; using system. text; using system. windows. forms; // Add the namespace using system. net; using system. net. sockets; using system. io; using system. threading; namespace syncchatclient {public partial class mainform: FORM {private bool isexit = false; private tcpclient client; private binaryr Eader BR; private binarywriter bw; Public mainform () {initializecomponent (); random r = new random (INT) datetime. now. ticks); textboxusername. TEXT = "user" + R. next (100,999); listboxonlinestatus. horizontalscrollbar = true;} // click the private void buttonconnect_click (Object sender, eventargs e) {buttonconnect. enabled = false; try {// This is a convenient demonstration. In actual use, you must set DNS. change gethostname () to server domain name client = N EW tcpclient (DNS. gethostname (), 51888); addtalkmessage ("connection successful");} catch {addtalkmessage ("connection failed"); buttonconnect. enabled = true; return;} // obtain the network stream networkstream = client. getstream (); // use the network stream as a binary read/write object; BR = new binaryreader (networkstream); BW = new binarywriter (networkstream); sendmessage ("login," + textboxusername. text); thread threadreceive = new thread (New threadstart (receivedata); t Hreadreceive. isbackground = true; threadreceive. start () ;}// Process accepted server-side data private void receivedata () {string receivestring = NULL; while (isexit = false) {try {// read the string receivestring = BR from the network stream. readstring ();} catch {If (isexit = false) {MessageBox. show ("lost contact with the server. ");} break;} string [] splitstring = receivestring. split (','); string command = splitstring [0]. tolower (); Switch (command) {case" Login ": addonline (splitstring [1]); break; Case" logout ": removeusername (splitstring [1]); break; Case" talk ": addtalkmessage (splitstring [1] + ": \ r \ n"); addtalkmessage (receivestring. substring (splitstring [0]. length + splitstring [1]. length + 2); break; default: addtalkmessage ("What do you mean:" + receivestring); break ;}} application. exit ();} // send the message private void sendmessage (string message) to the server {try {// send the character This method automatically appends the string length prefix BW. Write (Message); BW. Flush ();} catch {addtalkmessage ("failed to send! ") ;}} Private delegate void messagedelegate (string message); // append the chat information private void addtalkmessage (string message) {If (richtextboxtalkinfo. invokerequired) {messagedelegate d = new messagedelegate (addtalkmessage); richtextboxtalkinfo. invoke (D, new object [] {message});} else {richtextboxtalkinfo. appendtext (Message + environment. newline); richtextboxtalkinfo. scrolltocaret () ;}} PR Ivate delegate void addonlinedelegate (string message); // Add other online client information in listboxonlinestatus private void addonline (string username) {If (listboxonlinestatus. invokerequired) {addonlinedelegate d = new addonlinedelegate (addonline); listboxonlinestatus. invoke (D, new object [] {username});} else {listboxonlinestatus. items. add (username); listboxonlinestatus. selectedindex = listboxonlinestatus. items. Count-1; listboxonlinestatus. clearselected () ;}} private delegate void removeusernamedelegate (string username); // remove other offline client information from listboxonlinestatus private void removeusername (string username) {If (listboxonlinestatus. invokerequired) {removeusernamedelegate d = removeusername; listboxonlinestatus. invoke (D, username);} else {listboxonlinestatus. items. remove (username); listboxonlinestatus. s Electedindex = listboxonlinestatus. Items. Count-1; listboxonlinestatus. clearselected () ;}} private void buttonsend_click (Object sender, eventargs e) {If (listboxonlinestatus. selectedindex! =-1) {sendmessage ("talk," + listboxonlinestatus. selecteditem + "," + textboxsend. text + "\ r \ n"); textboxsend. clear ();} else {MessageBox. show ("select an operator in [current online] First"); }}// events triggered when the window is closed private void mainform_formclosing (Object sender, formclosingeventargs E) {If (client! = NULL) {sendmessage ("logout," + textboxusername. text); isexit = true; BR. close (); BW. close (); client. close () ;}// press enter in the message sending text box to trigger the event private void textboxsend_keypress (Object sender, keypresseventargs e) {If (E. keychar = (char) keys. return) {buttonsend. required mclick ();}}}}
So far, the program has been compiled.
Resource download link: http://download.csdn.net/detail/scrystally/4730653