Java Chat Room 1.0 (multi-threaded) (annotated version)

Source: Internet
Author: User

Client

Tftxt.addactionlistener (New Tflistener ()); The light punctuation in the input box to enter the time--and execute 67actionPerformed (ActionEvent e) method, change the method to send the input, of course, before the issue of the first to execute connect.

To exit is to first call 30disconnect () This method, first disconnect the connection

1 Importjava.awt.*;2 Importjava.awt.event.*;3 Importjava.io.IOException;4 Importjava.net.*;5 ImportJava.io.*;6  Public classChatClientextendsframe{7     8Socket s=NULL;9DataOutputStream dos=NULL;Ten      OneTextField tftxt=NewTextField ();//only one line can be written, there is an action ATextArea tacontent=NewTextArea ();//tags define multiple lines of text input controls -      -  the      Public Static voidMain (string[] args) { -         Newchatclient ().   Launchframe ();  -     } -      +      Public voidLaunchframe () -     { +SetLocation (400,300); A          This. SetSize (300,300); at Add (tftxt,borderlayout.south); - Add (Tacontent,borderlayout.north); - pack (); -          This. Addwindowlistener (NewWindowadapter () {//Close Window -  - @Override in              Public voidwindowclosing (windowevent e) { - disconnect (); toSystem.exit (0); +             } -              the});//Anonymous Class *Tftxt.addactionlistener (NewTflistener ()); $SetVisible (true);Panax Notoginseng Connect (); -     } the      +      Public voidConnect () A     { the         Try { +s=NewSocket ("127.0.0.1", 8888); -dos=NewDataOutputStream (S.getoutputstream ()); $System.out.println ("connected!"); $}Catch(unknownhostexception e) { - e.printstacktrace (); -}Catch(IOException e) { the e.printstacktrace (); -         }Wuyi          the     } -      Wu      Public voidDisconnect ()//Close Method -     { About         Try{ $ dos.close (); - S.close ();  -}Catch(IOException e) { - e.printstacktrace (); A         } +          the  -     } $     Private classTflistenerImplementsActionListener the     { the          Public voidactionperformed (ActionEvent e) {//One hit Enter theString str=tftxt.gettext (). Trim (); the Tacontent.settext (str); -Tftxt.settext ("");//empty after carriage return in             Try { the                 //dataoutputstream dos=new DataOutputStream (S.getoutputstream ()); theDos.writeutf (str);//output the stream. About Dos.flush (); the                 //dos.close (); the}Catch(IOException E1) { the e1.printstacktrace (); +             } -              the             Bayi         } the          the}//Inner class -}

Server Side

Importjava.net.*;ImportJava.io.*; Public classChatserver {BooleanStarted=false;//there's no monitoring.ServerSocket ss=NULL;//Initialize             Public Static voidMain (string[] args) {Newchatserver (). Start (); }             Public voidstart () {Try{SS=NewServerSocket (8888);//Port number 8888,TCP, listening on port 8888Started=true;//Connect on}Catch(bindexception e) {System.out.println ("Port in Use"); System.exit (0); }Catch(IOException e) {e.printstacktrace ();//gives the method's calling program, until the exception is generated.        }        Try{                         while(started)//has started{Socket s=ss.accept ();//a connection has been initiated to receive clients continuouslyClient c=NewClient (s);//after receiving a thread that comes upSYSTEM.OUT.PRINTLN ("A client connected!"); NewThread (c). Start ();//let this thread start, serve it//dis.close ();                }                            }Catch(IOException e) {e.printstacktrace (); }finally{                Try{ss.close (); }Catch(IOException e) {e.printstacktrace (); }            }    }    }        classClientImplementsrunnable{//thread Inner class                PrivateSocket s;//Each client is packaged with a separate socket, a semi-connected        PrivateDataInputStream dis=NULL;//each client retains its own inputstream; the input pipeline from which the contents of the socket are gambled//Keep a connection of your own        Private BooleanBconnected=false;//if it is connected, initialize false         PublicClient (Socket s) {//Pass the Socket property, constructor             This. s=s;//Initialize            Try{dis=NewDataInputStream (S.getinputstream ());//InitializeBconnected=true;//equals True after the connection}Catch(IOException e) {//TODO auto-generated Catch blockE.printstacktrace (); }        }                             Public voidRun () {//separate threads for individual client services//becomes true after receiving the other party            Try{               while(bconnected) {//there's something to attend.String Str=dis.readutf ();//blocked, accept the string that the client gave me and printSystem.out.println (str); }            }Catch(eofexception e) {System.out.println ("Client closed!"); }             Catch(IOException e) {e.printstacktrace (); }finally{                Try{                    if(Dis! =NULL) Dis.close (); }Catch(IOException E1) {e1.printstacktrace (); }            }                    }    }

Java Chat Room 1.0 (multi-threaded) (annotated version)

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.