Chat applet written with socket

Source: Internet
Author: User
Tags sendmsg

What is a socket?

It's a socket, but I'm not sure, but I'll skip it.

Directly on the instance, first the service side:

 Private intServerpoint =8102;//Custom Port Numbers Private stringServeruser ="Tracy";//Custom Nickname PrivateSocket Clientsk;Private Delegate voidAppendrich (stringTxtstringuser);//The delegate is defined to avoid "RichTextBox1 not created" error message when AppendText Private voidForm1_Load (Objectsender, EventArgs e) {Thread Listenthread=NewThread (NewThreadStart (appinit)); Listenthread.start (); //multithreading is used to prevent SK. Listen (10) has been in the listening state, causing the UI interface to die } Private voidAppinit () {Socket SK=Newsockets (AddressFamily.InterNetwork, SocketType.Stream, protocoltype.tcp); EndPoint EndPoint=NewIPEndPoint (Ipaddress.any, serverpoint); Sk. Bind (EndPoint); //instantiate the socket and bind the portSk. Listen (Ten);//start listening, if no client connection will remain stuck in thisClientsk= sk. Accept ();//Client Connection, assign this valid socket connection to the global variable Clientsk, the program continues to goSendmsg ("successfully connected to the server","System Messages"); Appendrich Dele=NewAppendrich (Appendtorich);//instantiate a delegate             while(true)//stay on the phone with a dead loop .            {                Try                {                    byte[] Receivebt =New byte[1024x768]; intReceiveint = Clientsk.receive (RECEIVEBT);//gets the received message                    if(Receiveint = =0)//If you receive an empty message, jump out of the loop                    {                         Break; }                    stringReceivestr = Encoding.UTF8.GetString (RECEIVEBT,0, Receiveint);//received message converted to stringRichtextbox1.invoke (Dele,New Object[] {receivestr.substring (9), Receivestr.substring (0,9). Trim ()});//added to Richbox, where I customize the format of the string, the nickname and the message content                }                Catch(Exception ex) { Break; }            }            //this jumps out of the loop, which means the program is about to closeClientsk.close ();//close the socket connected to the clientSk. Close ();//close the instantiated socketRichtextbox1.invoke (Dele,New Object[] {"The connection has been terminated","System Messages"});//to add a string to a RichTextBox1 with a delegate } Private voidSendmsg (stringTxtstringuser) {            stringNickname =user; stringSendstr = Nickname.padleft (9) +txt; byte[] bs =Encoding.UTF8.GetBytes (SENDSTR); Clientsk.send (BS, BS. Length,0);//send a message to the client } Private voidAppendtorich (stringTxtstringuser) {            if(txt = =string. Empty) {return; } richtextbox1.appendtext ("\ r \ n"+ user +" "+ DateTime.Now.ToString ("HH:mm:ss") +"\ r \ n"+txt); Richtextbox1.scrolltocaret ();//scroll bar remains at the bottomTextbox2.resettext (); Textbox2.focus (); }
Servercode

Client:

 Private intServerpoint =8102;//Customize the port number to match the previous server Private stringClientuser ="Knorr-Bremse", ClientIP ="127.0.0.1";//custom nicknames, and server-side IP PrivateSocket newclient;Private Delegate voidAppendrich (stringTxtstringuser); Private voidForm1_Load (Objectsender, EventArgs e) {Thread Listenthread=NewThread (NewThreadStart (appinit)); Listenthread.start (); } Private voidAppinit () {newclient=Newsockets (AddressFamily.InterNetwork, SocketType.Stream, protocoltype.tcp); IPEndPoint ie=NewIPEndPoint (Ipaddress.parse (ClientIP), serverpoint);//IP and port of the serverNewclient. Connect (IE);//There is no need to bind and connect directly to the server            stringHostname= Dns.gethostname ();//get the client host nameIphostentry Iphostentry =dns.gethostentry (hostName); List<IPAddress> Ips=iphostentry. Addresslist.tolist ();//Get client IPsendmsg (ips[2]. ToString () +"is connected","System Messages"); Appendrich Dele=NewAppendrich (Appendtorich);  while(true)            {                Try                {                    byte[] Receivebt =New byte[1024x768]; intReceiveint = newclient. Receive (RECEIVEBT);//gets the received message                    if(Receiveint = =0)                    {                         Break; }                    stringReceivestr = Encoding.UTF8.GetString (RECEIVEBT,0, Receiveint);//received message converted to stringRichtextbox1.invoke (Dele,New Object[] {receivestr.substring (9), Receivestr.substring (0,9). Trim ()});//Add to Richbox                }                Catch(Exception ex) { Break; }} newclient.            Close (); Richtextbox1.invoke (Dele,New Object[] {"The connection has been terminated","System Messages" }); } Private voidSendmsg (stringTxtstringuser) {            stringNickname =user; stringSendstr = Nickname.padleft (9) +txt; byte[] bs =Encoding.UTF8.GetBytes (SENDSTR); Newclient. Send (BS, BS. Length,0);//Send Message } Private voidAppendtorich (stringTxtstringuser) {            if(txt = =string. Empty) {return; } richtextbox1.appendtext ("\ r \ n"+ user +" "+ DateTime.Now.ToString ("HH:mm:ss") +"\ r \ n"+txt); Richtextbox1.scrolltocaret ();//scroll bar remains at the bottomTextbox1.resettext (); Textbox1.focus (); }
Clientcode

Chat applet written with socket

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.