Java Simple chat Room 1.2

Source: Internet
Author: User
Tags gettext

System is exiting

Notify the server first, and let the server do what it does.

Stop the thread, listen for a while, time to cut off

Server Side

Importjava.net.*;ImportJava.io.*;ImportJava.util.*; Public classChatserver {BooleanStarted=false;//there's no monitoring.ServerSocket ss=NULL;//Initializelist<client>clients=NewArraylist<client>();  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 itClients.add (c); //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        PrivateDataOutputStream dos=NULL; 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 ());//Initializedos=NewDataOutputStream (S.getoutputstream ()); bconnected=true;//equals True after the connection}Catch(IOException e) {e.printstacktrace (); }        }                 Public voidSend (String str) {Try{dos.writeutf (str); } Catch(IOException e) {e.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);  for(intI=0;i<clients.size (); i++) {//Collection ClassClient c=Clients.get (i); C.send (str); System.out.println ("Made a statement."); }                                /*For (iterator<client> it=clients.iterator (); It.hasnext ();) {Client c=it.next ();                C.send (str); }*/                /*Iterator it=clients.iterator ();                    while (It.hasnext ()) {Client c=it.next ();                                    C.send (str); }//internal locking, no need for low efficiency*/               }            }Catch(eofexception e) {System.out.println ("Client closed!"); }             Catch(IOException e) {e.printstacktrace (); }finally{                Try{                    if(Dis! =NULL) Dis.close (); if(Dos! =NULL) Dos.close (); if(s!=NULL) {s.close (); //S=null;                    }                }Catch(IOException E1) {e1.printstacktrace (); }            }                    }    }}


Client

Importjava.awt.*;Importjava.awt.event.*;Importjava.io.IOException;Importjava.net.*;ImportJava.io.*; Public classChatClientextendsframe{Socket S=NULL; DataOutputStream dos=NULL; DataInputStream Dis=NULL; Private Booleanbconnected =false; TextField Tftxt=NewTextField ();//only one line can be written, there is an actionTextArea tacontent=NewTextArea ();//tags define multiple lines of text input controlsThread trecv=NewThread (NewRecvthread ());  Public Static voidMain (string[] args) {Newchatclient ().       Launchframe (); }         Public voidLaunchframe () {setlocation (400,300);  This. SetSize (300,300);        Add (Tftxt,borderlayout.south);        Add (Tacontent,borderlayout.north);        Pack ();  This. Addwindowlistener (NewWindowadapter () {//Close Window@Override Public voidwindowclosing (windowevent e) {disconnect (); System.exit (0); }                    });//Anonymous ClassTftxt.addactionlistener (NewTflistener ()); SetVisible (true);        Connect (); //New Thread (New Recvthread ()). Start ();Trecv.start (); }         Public voidConnect () {Try{s=NewSocket ("127.0.0.1", 8888); DOS=NewDataOutputStream (S.getoutputstream ()); Dis=NewDataInputStream (S.getinputstream ());//InitializeSystem.out.println ("connected!"); bconnected=true; } Catch(unknownhostexception e) {e.printstacktrace (); } Catch(IOException e) {e.printstacktrace (); }            }         Public voidDisconnect ()//Close Method    {        Try{dos.close ();          Dis.close ();          S.close (); }Catch(IOException e) {e.printstacktrace (); }                        /*try{bconnected=false;//Close thread trecv.join ();//merge}catch (interruptedexceptio        n e) {e.printstacktrace ();             }finally{try{dos.close ();            Dis.close ();        S.close ();            }catch (IOException e) {e.printstacktrace (); }        }*/    }    Private classTflistenerImplementsActionListener { Public voidactionperformed (ActionEvent e) {//One hit EnterString str=tftxt.gettext (). Trim (); //Tacontent.settext (str);Tftxt.settext ("");//empty after carriage return            Try {                //dataoutputstream dos=new DataOutputStream (S.getoutputstream ());Dos.writeutf (str);//output the stream.Dos.flush (); //dos.close ();}Catch(IOException E1) {e1.printstacktrace (); }                    }                }//Inner class    Private classRecvthreadImplementsrunnable{ Public voidrun () {Try{               while(bconnected) {String str=Dis.readutf ();                  System.out.println (str); Tacontent.settext (Tacontent.gettext ()+str+ ' \ n '); }            }Catch(SocketException e) {System.out.println (Exit); }Catch(IOException e) {e.printstacktrace (); }                    }    }}

Java Simple chat Room 1.2

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.