This is a simple chat room program I wrote with Java Socket. The following is my design document and source code:
Chatroom chat room design documentation
Client and server interface:
Client
Service-Terminal
Chatroom Chat Room Program Features Description:
The server accepts information sent by each connection customer and broadcasts to each customer.
Server:
Server ChatroomServer starts automatically listening to the default port: Default_port 6666 Wait for the customer's connection, when there is a client connection, display connection information in the text domain.
The server side click window to close or click the exit button in the window to turn off the server.
Client:
The client chatomClient is launched after displaying the client interface: There is a "connection" button and a text basket above the window (the text basket on the right side of the button). Enter the server address in the text basket, press the "Connection" button on the left or press the "Enter" button on the keyboard to connect the server. If the connection successfully displays the connection success information, the connection failed information will be displayed.
After the connection is successful, the customer can enter the message you want to send in the text basket on the right side of the form bottom message tag, then click the "Send" button on the right side of the text basket or press the "Enter" button on the keyboard.
The information received by the client will appear in the text field in the middle of the form.
ChatroomServer.java - Description:
// Due to more comments in the program, only simple narratives are made here:
1. The program starts is the initialization interface and start listening:
Public chatroomserver () {
Try {
Jbinit ();
} catch (exception e) {
E.PrintStackTrace ();
}
ServerListen (); // server start listening
}
Jbinit () {,,,,} Initialization interface, registration button and window shutdown event.
SERVERLISTEN () () {,,} Open and listen to ports: 6666,
2. Public void run () {// accepts connection and recording thread information
,,,,,
Try {
While (true) {
Socket clientsock = serversock.accept ();
CommunicateThread CT = New CommunicateThread (ClientSock, this, INDEX); // Creating a thread keep connection
Clients.add (ct); // Record connection information to the clients array
ClientsInfor.Add ("Thread -" i); // Record the connection name
, ,,,,,,,,,
}
CommunicateThread CT = New CommunicateThread (Clientsock, this, INDEX);
When there is a connection, create a thread to keep the connection.
3. Public void exit () {,,,}
Exit and close Seversock
4.Class CommunicateThread Extends Thread {,,,,} // Keep connection thread
5. Class Broadcastthread Extends Thread {,,} // broadcast thread
6. // Process the adapter for the window closing event
Class chatframe_windowadapter extends java.awt.event.windowadapter {,,,}
ChatroomClient.java - Description:
1. Initialization form
Public chatroomclient () {
Try {
Jbinit ();
} catch (exception e) {
E.PrintStackTrace ();
}
}
Jbinit () {,,,,} Initialization Form, register the button1 (Connection), button2 (send) to ActionListener, register the TextField1 (server address), TextField2 (message) to Keylistener, register the form to WindowListener.
2. STARTCONNECT () {,,,,} // Connect the server
Click Button1 or press "Enter" in TextField1 to call the startConnect () to connect the server and start the thread run (), read the information from the server broadcast, and print to the text area.
3. Public void exit () {,,,} // Window is closed; if you have a connection, turn off the connection and related "flow"
4. // Text Basket Textfield1 Key Event Adapter
Class textfield1_keyadapter extends java.awt.event.keyadapter {}
5. // Text Basket Textfield2 Keyword Adapter
Class textfield2_keyadapter extends java.awt.event.keyadapter {}
6. // Window Close Event Adapter
Class chatframe_windowadapter extends java.awt.event.windowadapter {}
Chat Room Server End Program:
Package chatServer2; // chat room server // this Software is designed by Chen Heping (Chen Heping)
Import java.awt. *; import java.awt.event. *; import java.io. *; import java.net. *;
public class ChatRoomServer extends Frame implements Runnable {Panel panel; ScrollPane sPanel; TextArea textArea; Button button1; // net ServerSocket serverSock; public final static int DEFAULT_PORT = 6666; // default port number Thread chatAcceptThread; // start receiving the thread connection BroadcastThread Broadcastthread; // Broadcast Thread; Run When Server is listening java.util.vector clients; // Record connection thread java.util.Vector clientsinfor; // Record connection thread information public static int index = 0; public chatroomserver () {Try {jbinit ();} catch (exception e) {E.PrintStackTrace ();} serverListen (); // server start listening} private void jbinit () {// Initialization interface panel = new panel (); spanel = New scrollpane (); textarea = new textarea ("Server Information: / N"); Button1 = New Button ("Exit"); spnel.add (TextArea); button1.addactionListener (new java.awt.event.ActionListener () {// Exit button Register Public Void ActionPerformed (ActionEvent E) {Button1_ActionPerformed (e);}}); Panel.Add (Button1); this.addWindowListener (new chatframe_windowadapter (this)); // Register to inherit the window adapter THIS.SETSIZE (600, 600); this.SetLayout (New borderLayout ()); this.add (spanel, borderlayout.ceter); this.add (Panel, borderLayout.South); this.show ();} private void button1_actionperformed (ActionEvent E) { exit ();} public void processMsg (String str) {// textArea.append (str);} private void serverListen () {try {serverSock = new ServerSocket (DEFAULT_PORT);} catch (IOException e) {processMsg (e. Totring ()); Processmsg ("Server Failed! / N");} Processmsg ("Server Listening On Port: Default_Port); Clients = new java.util.Vector (); clientsinfor = new java.util.Vector ); Chatacceptthread = new thread (this); // Start accepting thread chatacceptthread.Start (); Broadcastthread =
New Broadcastthread (this); // broadcast thread BroadcastthRead.start (); // There is also a recycling useless connection thread thread} public void run () {// Accept connection and recording thread information int i = 0; try {while (true) {Socket clientSock = serverSock.accept (); CommunicateThread ct = new CommunicateThread (clientSock, this, index); // Create a thread remains connected clients.add (ct); // record Communicate thread; i ; index ; / / Version2 ClientsInfor.Add ("Thread -" i); Processmsg ("Thread -" i "join in / n");}}} Catch (ooException E) {processmsg (e.toString ());}} public Void EXIT () {Broadcastthread.Broadcast ("Server EXIT!"); try {serversock.close ();} catch (ooException ie) {} finally {system.exit (0);}} public static void main (String " ] args) {chatroomserver chat = new chatroomserver ();}}
class CommunicateThread extends Thread {// holding connection thread protected Socket clientSock; protected BufferedReader in = null; protected PrintWriter out; ChatRoomServer chatFrame; boolean isTrue = true; // run () java.util.Vector inforStack; int index2; // public CommunicateThread (Socket Sock, ChatRoomServer cFrame, int index) {clientSock = Sock; chatFrame = cFrame; index2 = index; inforStack = new java.util.Vector (); try {in = new BufferedReader (new InputStreamReader (clientSock.getInputStream () )); out = new PrintWriter (clientSock.getOutputStream ());} catch (IOException ei) {try {clientSock.close ();} catch (IOException ei2) {} chatFrame.processMsg (ei.toString ()); return This.Start ();} public void run () {string infor; try {while (istrue) {INFOR = in.readline (); if (Infor.Equals ("Client Exit!")) {WRITEINFORMATION ); // Write the information to the information stack, broadcast STOPRUN ();} else if (infor! = Null) {WRITEINFORMATION (INFOR);} // else break; try {thread.sleep (100); / / Version2} catch (Interruptede Xception ex) {}}} catch (} finally {uin.close (); out.close (); clientsock.close (); chatframe.clients.remove (index2); // In Clients Clear the online program chatroomserver.index -; //} catch (ooException ei) {;}}} public void writeinformation (String Infor) {// Write InforStack.Add (Infor); {// Termination Thread Istrue = False;} Public Void Sendinformation (String Str) {// Send Information Try {Out.Println (Str); Out.Flush ();} Catch (Exception E) {;}}}
class BroadcastThread extends Thread {// broadcast thread ChatRoomServer chatFrame2; java.util.Vector chatClients; // connection thread information java.util.Vector msgStack; // stack information java.util.Vector clientMsg; // record the information sent by the client CommunicateThread comThread1; CommunicateThread comThread2; String string; // information in inforStack String clientName; // client thread name String broadcastInfor; // broadcast information = clientName string; public BroadcastThread (ChatRoomServer cFrame) {chatFrame2 = cFrame; chatClients = chatFrame2.clients; Clientmsg = chatframe2.clientsinfor; //this.Start ();} public void Broadcast (String Str) {// broadcast for (int K = 0; k
// processing window closing event adapter class ChatFrame_WindowAdapter extends java.awt.event.WindowAdapter {ChatRoomServer chatFrame; public ChatFrame_WindowAdapter (ChatRoomServer chatFrame) {this.chatFrame = chatFrame;} public void windowClosing (WindowEvent e) {// exit program chatFrame. EXIT (); // Reference to the method exit () in chatroomserver.}}
Package chatclient_test; // chatroomclient // designed by chen Heping (Chen Heping)
Import java.awt. *; import java.awt.event. *; import java.io. *; import java.net. *;
public class ChatRoomClient extends Frame implements Runnable {Panel panel1, panel2; Button button1, button2; TextField textField1, textField2; Label label1; TextArea textArea; ScrollPane sPanel; // net PrintWriter out; BufferedReader in = null; Socket sock; public final static int DEFAULT_PORT = 6666; // create Thread to Read information from Server Thread readThread; boolean isTrue = true; // thread can go on runing ?? public ChatRoomClient () {try {jbInit ();} catch (Exception e) {e. PRINTSTACKTRACE ();}} public static void main (String [] args) {// main method chatroomclient c = new chatroomclient (); C.Show ();} private void jbinit () {// shop set size, position and Font of every component button1 = new button); // set font button2 = new button ("send"); TextField1 = New TextField ("Input Server Address Here!"; TextField2 = New TextField ("Input Message Here and send to server "); label1 = new label (" message: "); panel1 = new panel (); panel2 = new panel (); spanel = new scrollpane (); textarea = new textar ea (); // panel1 // press button1: connection to connect the client to server button1.addActionListener (new java.awt.event.ActionListener () {public void actionPerformed (ActionEvent e) {button1_actionPerformed (e);}}) ; // textField1: for input the address of server; be registered to KeyListener // press key:. Enter to connect the client to server textField1.addKeyListener (new textField1_KeyAdapter (this)); // java.awt.event.KeyAdapter ( Panel1.Add (Button1); Panel1.add (TextField1); // Spanel Scrollpane Spnel.Add (Textarea);
// panel2 // press button2: transmitting to send message button2.addActionListener (new java.awt.event.ActionListener () {public void actionPerformed (ActionEvent e) {button2_actionPerformed (e);}}); // textField2: for input message; be registered to KeyListener // press key: Enter to send message textField2.addKeyListener (new textField2_KeyAdapter (this)); panel2.add (label1); panel2.add (textField2); panel2.add (button2); //. frame this.addWindowListener (new ChatFrame_WindowAdapter (this)); // frame is registered to WindowListener this.setLayout (new BorderLayout ()); this.setSize (500,400); this.add (panel1, BorderLayout.NORTH); this.add (Spander, BorderLayout.center); this.add (Panel2, BorderLayout.South); //this.show ()} public void startconnect () {// Start connecting try {sock = new socket (TextField1.getText (), DEFAULT_PORT); if (sock = null) {// connection successed processMsg ( "Connect successfully!");}! in = new BufferedReader (new InputStreamReader (sock.getInputStream ())); out = new PrintWrite r (Sock.getOutputStream ());} catch (ioException ex) {processmsg (ex.Tostring ()); Processmsg ("Connect Failed!");} Readthread = New Thread (this); readthread.Start ();} // public void endConnect () {// close iOstream public void sendInformation () {out.println (textField2.getText ()); out.flush ();} private void button1_actionPerformed (ActionEvent e) {// connect button startConnect ( );} private void button2_actionPerformed (ActionEvent e) {// send button sendInformation ();} public void stopRun () {// to stop the running thread isTrue = false;} public void processMsg (String msg) {// client Processing Message TextArea.Append (MSG); TextArea.Append ("/ n");} public void Run () {string msg; istrue = true;
While (istrue) {try {msg = IN.Readline (); if (Msg.Equals ("Server EXIT!")) {// server exit processmsg (msg); stoprun (); // termination thread} else IF Msg! = null) {processmsg (msg);} thread.sleep (1000);} catch (ooException e) {processmsg (e.tostring ());} catch (interruptedException EI) {processmsg (ei.tostring ()) ;}} // endConnect (); try {// server exits the "flow" sock.close (); in .close (); out.close ();} catch ({ion ();}}}} Public void exit () {// window is closed; if there is a connection, turn off the connection and related "stream" Try {// send "client exit!" to Server! Out.println ("Client Exit!"); Out.Flush ();} CatCh (Exception Exc) {} // endconnect (); try {// close iostream sock.close (); in .close (); out.close ();} catch (} catch (ooException ie) {} finally {System.exit (0);}}} // text housing textField1 keystroke event adapter class textField1_KeyAdapter extends java.awt.event.KeyAdapter {ChatRoomClient chatFrame; public textField1_KeyAdapter (ChatRoomClient chatFrame) {this.chatFrame = chatFrame;} public Void keypressed (keyevent e) {// entered Enter, open Start connection! INT J = E.GetKeycode (); if (j == E.VK_ENTER) {chatframe.startconnect ();}}}
// Text basket textField2 keystroke event adapter class textField2_KeyAdapter extends java.awt.event.KeyAdapter {ChatRoomClient chatFrame; public textField2_KeyAdapter (ChatRoomClient chatFrame) {this.chatFrame = chatFrame;} public void keyPressed (KeyEvent e) {// keystroke ENTER button, send information! INT j = E.GetKeycode (); if (j == E.vk_enter) {chatframe.sendinformation ();}}}