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 ();}}}