Java Chat Room Code

Source: Internet
Author: User

Chat Room Interface:

Source:

 Public  class clientframe extends Frame {    PrivateTextField textfieldcontent =NewTextField ();PrivateTextArea textareacontent =NewTextArea ();PrivateSocket socket =NULL;PrivateOutputStream out =NULL;PrivateDataOutputStream dos =NULL;PrivateInputStream in =NULL;PrivateDataInputStream dis =NULL;Private BooleanFlag =false;/** * School: Shandong Normal University programmer: External Force _victor Date: May 8, 2016 9:19:51 function: Start the client program * * @param args */     Public Static void Main(string[] args) {NewClientframe (). Init (); }/** * School: Shandong Normal University programmer: External Force _victor Date: May 8, 2016 9:20:43 function: Initialize the window */    Private void Init() { This. SetSize ( -, -); SetLocation ( -, Max); SetVisible (true); Settitle ("Wechatroom");//Add control         This. Add (Textareacontent); This. Add (Textfieldcontent, Borderlayout.south); Textareacontent.setfocusable (false); Pack ();//Close eventAddwindowlistener (NewWindowadapter () { Public void windowclosing(WindowEvent e) {System.out.println ("The user tried to close the window");                Disconnect (); System.exit (0); }        });//textfieldcontent Add carriage return eventTextfieldcontent.addactionlistener (NewActionListener () { Public void actionperformed(ActionEvent e)            {Onclickenter (); }        });//Establish connectionConnect ();NewThread (NewRecivemessage ()). Start (); }Private  class recivemessage implements Runnable {        @Override         Public void Run() {flag =true;Try{ while(flag)                    {String message = Dis.readutf (); Textareacontent.append (Message +"\ n"); }            }Catch(Eofexception e) {flag =false; System.out.println ("Client is down");//E.printstacktrace ();}Catch(SocketException e) {flag =false; System.out.println ("Client is down");//E.printstacktrace ();}Catch(IOException e) {flag =false; System.out.println ("Accept message Failed");            E.printstacktrace (); }        }    }/** * Function: When you click on the carriage return event School: Shandong Normal University programmer: External Force _victor Date: May 8, 2016 morning 9:49:30 * *    Private void Onclickenter() {String message = Textfieldcontent.gettext (). Trim ();if(Message! =NULL&&!message.equals ("")) {String time =NewSimpleDateFormat ("H:m:s"). Format (NewDate ()); Textareacontent.append (Time +"\ n"+ Message +"\ n"); Textfieldcontent.settext ("");        Sendmessagetoserver (message); }    }/** * Function: Send message to server school: Shandong Normal University programmer: External Force _victor Date: May 8, 2016 morning 10:13:48 * * @param Message * *    Private void Sendmessagetoserver(String message) {Try{DOS.WRITEUTF (message);        Dos.flush (); }Catch(IOException e) {System.out.println ("Send message Failed");        E.printstacktrace (); }    }/** * Function: Apply for Socket link School: Shandong Normal University programmer: External Force _victor Date: May 8, 2016 morning 10:00:38 * *    Private void Connect() {Try{socket =NewSocket ("localhost",8888);            out = Socket.getoutputstream (); DOS =NewDataOutputStream (out);            in = Socket.getinputstream (); dis =NewDataInputStream (in); }Catch(Unknownhostexception e) {System.out.println ("Request link Failed");        E.printstacktrace (); }Catch(IOException e) {System.out.println ("Request link Failed");        E.printstacktrace (); }    }/** * Function: Close stream and link school: Shandong Normal University programmer: External Force _victor Date: May 8, 2016 morning 10:01:32 * *    Private void Disconnect() {flag =false;if(Dos! =NULL) {Try{Dos.close (); }Catch(IOException e) {System.out.println ("DOS shutdown failed");            E.printstacktrace (); }        }if(Out! =NULL) {Try{Out.close (); }Catch(IOException e) {System.out.println ("DOS shutdown failed");            E.printstacktrace (); }        }if(Socket! =NULL) {Try{Socket.close (); }Catch(IOException e) {System.out.println ("Socket shutdown failed");            E.printstacktrace ();        }            ; }    }}
 PackageCom.chat;ImportJava.io.DataInputStream;ImportJava.io.DataOutputStream;ImportJava.io.EOFException;ImportJava.io.IOException;ImportJava.io.InputStream;ImportJava.io.OutputStream;ImportJava.net.BindException;ImportJava.net.ServerSocket;ImportJava.net.Socket;ImportJava.net.SocketException;ImportJava.util.ArrayList;ImportJava.util.List; Public  class chatserver {    Privatelist<client> clients =NewArraylist<> ();/** * Function: Start chatsever School: Shandong Normal University programmer: External Force _victor Date: May 8, 2016 morning 10:26:41 * * @param args */     Public Static void Main(string[] args) {NewChatserver (). Init (); }/** * Function: To Chatserver initialization school: Shandong Normal University programmer: External Force _victor Date: May 8, 2016 morning 10:27:09 * *    Private void Init() {System.out.println ("Server is turned on");//BindexceptionServerSocket SS =NULL; Socket socket =NULL;Try{SS =NewServerSocket (8888); }Catch(Bindexception e) {System.out.println ("Port is already occupied");        E.printstacktrace (); }Catch(IOException E1)        {E1.printstacktrace (); }Try{Client Client =NULL; while(true) {socket = ss.accept (); System.out.println ("Customer Arrivals"); Client =NewClient (socket); Clients.add (client);NewThread (client). Start (); }        }Catch(IOException e)        {E.printstacktrace (); }    }Private  class Client implements Runnable {        PrivateSocket socket =NULL; InputStream in =NULL; DataInputStream din =NULL; OutputStream out =NULL; DataOutputStream dos =NULL;BooleanFlag =true; Public Client(Socket socket) { This. socket = socket;Try{in = Socket.getinputstream (); DIN =NewDataInputStream (in); }Catch(IOException e) {System.out.println ("Accept message Failed");            E.printstacktrace (); }        } Public void Run() {String message;Try{ while(flag) {message = Din.readutf ();//SYSTEM.OUT.PRINTLN ("Customer said:" + message);forwordtoallclients (message); }            }Catch(SocketException e) {flag =false; System.out.println ("Customer Downline"); Clients.remove ( This);//E.printstacktrace ();}Catch(Eofexception e) {flag =false; System.out.println ("Customer Downline"); Clients.remove ( This);//E.printstacktrace ();}Catch(IOException e) {flag =false; System.out.println ("Accept message Failed"); Clients.remove ( This);            E.printstacktrace (); }if(DIN! =NULL) {Try{Din.close (); }Catch(IOException e) {System.out.println ("din shutdown failed");                E.printstacktrace (); }            }if(In! =NULL) {Try{In.close (); }Catch(IOException e) {System.out.println ("din shutdown failed");                E.printstacktrace (); }            }if(Socket! =NULL) {Try{Socket.close (); }Catch(IOException e) {System.out.println ("din shutdown failed");                E.printstacktrace (); }            }        }/** * Function: forward to all clients school: Shandong Normal University programmer: External Force _victor Date: May 8, 2016 morning 11:11:59 * * @param Message * @throws ioexception * *        Private void forwordtoallclients(String message)throwsIOException { for(Client c:clients) {if(c! = This) {out = C.socket.getoutputstream (); DOS =NewDataOutputStream (out);                Forwordtoclient (message); }            }        }/** * Function: Send to a client school: Shandong Normal University programmer: External Force _victor Date: May 8, 2016 morning 11:16:12 * * @throws ioexce ption * *        Private void forwordtoclient(String message)throwsIOException {DOS.WRITEUTF (message);            Dos.flush (); System.out.println ("forwarded successfully!" "); }    }}

SOURCE Download: http://download.csdn.net/detail/qq_24082497/9513776

Java Chat Room 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.