TCP Small Instant Chat message program, C #-based program, server-side code

Source: Internet
Author: User

namespacesyncchatserver{classUser { PublicTcpClient client{Get;Private Set;}  PublicBinaryReader br{Get;Private Set;}  PublicBinaryWriter bw{Get;Private Set;}  Public stringUserName {Get;Set; }  PublicUser (TcpClient client) { This. Client =client; NetworkStream NetworkStream=client.            GetStream (); BR=NewBinaryReader (NetworkStream); Bw=NewBinaryWriter (NetworkStream); }         Public voidClose () {br.            Close (); Bw.            Close (); Client.        Close (); }}}//Declares a customer's class user
Using system;using system.collections.generic;using system.windows.forms;//added namespace reference using System.net;using system.net.sockets;using system.threading;namespace syncchatserver{public partial class Mainform:form {//        /<summary> Save all users connected </summary> private list<user> userlist = new list<user> ();        <summary> native IP address used by </summary> IPAddress localaddress;        <summary> Listening port </summary> Private Const int port = 51888;        Private TcpListener MyListener;        <summary> whether to exit all receive threads normally </summary> bool Isnormalexit = false;            Public MainForm () {InitializeComponent ();            Listboxstatus.horizontalscrollbar = true;            ipaddress[] Addrip = dns.gethostaddresses (Dns.gethostname ());            localaddress = addrip[0];        buttonstop.enabled = false; }///<summary> Start listening button's Click event </summary> private void buttonStart_click (object sender, EventArgs e) {mylistener = new TcpListener (localaddress, Port);            Mylistener.start (); Call a static method of string to specify the format of the output Additemtolistbox (string.            Format ("Start monitoring client connection at {0}:{1}", localaddress, Port));            Create a thread to listen for client connection requests Thread MyThread = new Thread (listenclientconnect);            Mythread.start ();            buttonstart.enabled = false;        Buttonstop.enabled = true; }///<summary> receive client connection </summary> private void Listenclientconnect () {Tcpclien            T newclient = null; while (true) {try {//In the server, the TcpClient object must be accepttcpclient ();                Method Get newclient = Mylistener.accepttcpclient (); } catch {//When you click Stop listening or exit this form accepttcpclient () will produce an exception//                Therefore, this exception can be used to exit the loop break; }                Each time a client connection is received, a corresponding thread is created to loop over the information sent by the client 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 number of connected users: {0}", Userlist.count)); }}///<summary>//Processing client data Received///</summary>//<param name= "UserState" &            gt; client information </param> private void Receivedata (object userState) {User user = (user) userState;            TcpClient client = user.client;                while (Isnormalexit = = False) {string receivestring = null; try {///reads the string from the network stream, this method automatically determines the string length prefix and reads the string receivestring = user based on the length prefix. Br.                ReadString (); } catch               {if (Isnormalexit = = False) {Additemtolistbo X (String. Format ("with [{0}] lost contact, terminated receiving this user information", client.                        Client.remoteendpoint));                    Removeuser (user);                } break; } additemtolistbox (String.                Format ("from [{0}]:{1}", User.client.Client.RemoteEndPoint, receivestring));                string[] splitstring = Receivestring.split (', '); Switch (splitstring[0]) {case "Login": User.username = Splitstri                        NG[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} said: {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 (tar                                Get, "talk," + User.username + "," + talkstring);                            Break                    }} break;                        Default:additemtolistbox ("What do you mean:" + receivestring);                Break }}}///<summary>//Send message to User///</summary>//&LT;PA Ram name= "User" > Specify which user to send </param>            <param name= "message" > Information content </param> private void sendtoclient (user user, String message) {                try {//writes a string to the network stream, this method automatically appends the string length prefix user.bw.Write (message);                User.bw.Flush (); Additemtolistbox (String.            Format ("Send to [{0}]: {1}", User.username, message)); } catch {Additemtolistbox (string.            Format ("Sending information to [{0}] failed", user.username));        }}///<summary> send information to all customers </summary>//<param name= "User" > Specify which user to send </param>        <param name= "message" > Information content </param> 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 the login information is sent to each user this information if (U Serlist[i].username! = user.username)//If it is the login information, it will also be sent to the user who will be logged on the user's name {SENDTOCL                    Ient (User, "login," + userlist[i].username);                }}} else if (command== "logout")//If it is logged out, it is sent to each of the remaining user log-out information {                     for (int i = 0; i < Userlist.count; i++) {if (userlist[i].username! = user.username)                    {sendtoclient (userlist[i], message); }}}}///<summary> Remove users </summary>//<param name= "user" &G            t; Specify the user to delete </param> private void Removeuser (user user) {userlist.remove (user); User.            Close (); Additemtolistbox (String.        Format ("Current number of connected users: {0}", Userlist.count)); }        Private delegate void Additemtolistboxdelegate (String str); <summary> Append status information to the ListBox </summary>//<param name= "str" > Information to append </param> 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 (); }}///<summary> "Stop Listening" button for click event </summary> private void ButtonStop_Click (object sender,            EventArgs e) {Additemtolistbox ("Start to stop the service and let the user exit in turn!");            Isnormalexit = true;            for (int i = userlist.count-1; I >= 0; i--) {Removeuser (userlist[i]); }//By stopping the monitoring let MyliStener.            AcceptTcpClient () generates an abnormal exit listener thread mylistener.stop ();            Buttonstart.enabled = true;        buttonstop.enabled = false; }///<summary> event triggered when the window is closed </summary> private void Mainform_formclosing (object sender, FormClosing                EventArgs e) {if (MyListener! = null) {//Raises the Buttonstop click event            Buttonstop.performclick (); }        }    }}

  

TCP Small Instant Chat message program, C #-based program, server-side code

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.