Вы находитесь на странице: 1из 7

MULTI-THREADED ECHO SERVER PROGRAM import java.io.*; import java.net.

*; public class MultiThreadChatServer{ static Socket clientSocket = null; static ServerSocket serverSocket = null; static clientThread t[] = new clientThread[10]; public static void main(String args[]) { int port_number=2222; if (args.length < 1) { System.out.println("Usage: java MultiThreadChatServer \n"+ "Now using port number="+port_number); } else { port_number=Integer.valueOf(args[0]).intValue(); } try { serverSocket = new ServerSocket(port_number); } catch (IOException e) {System.out.println(e);} while(true){ try { clientSocket = serverSocket.accept(); for(int i=0; i<=9; i++){ if(t[i]==null) { (t[i] = new clientThread(clientSocket,t)).start(); break; } } } catch (IOException e) { System.out.println(e);} } } } class clientThread extends Thread{ DataInputStream is = null; PrintStream os = null; Socket clientSocket = null; clientThread t[]; public clientThread(Socket clientSocket, clientThread[] t){ this.clientSocket=clientSocket; this.t=t;

} public void run() { String line; String name; try{ is = new DataInputStream(clientSocket.getInputStream()); os = new PrintStream(clientSocket.getOutputStream()); os.println("Enter your name."); name = is.readLine(); os.println("Hello "+name+" to our chat room.\nTo leave enter /quit in a new line"); for(int i=0; i<=9; i++) if (t[i]!=null && t[i]!=this) t[i].os.println("*** A new user "+name+" entered the chat room !!! ***" ); while (true) { line = is.readLine(); if(line.startsWith("BYE")) break; for(int i=0; i<=9; i++) if (t[i]!=null) t[i].os.println("<"+name+"> "+line); } for(int i=0; i<=9; i++) if (t[i]!=null && t[i]!=this) t[i].os.println("*** The user "+name+" is leaving the chat room !!! ***" ); os.println("*** Bye ***"); for(int i=0; i<=9; i++) if (t[i]==this) t[i]=null; is.close(); os.close(); clientSocket.close(); } catch(IOException e){}; } } GUI CLIENT PROGRAM import java.io.*; import java.awt.*; import java.awt.event.*; import javax.swing.*; import java.net.*; public class TCPChat implements Runnable { public final static int NULL = 0; public final static int DISCONNECTED = 1; public final static int BEGIN_CONNECT = 2; public final static int CONNECTED = 3;

public final static String statusMessages[] = { " Error! Could not connect!", " Disconnected", " Connecting...", " Connected" }; public final static TCPChat tcpObj = new TCPChat(); public static String hostIP = "localhost"; public static int port = 2222; public static int connectionStatus = BEGIN_CONNECT; public static String statusString = statusMessages[connectionStatus]; public static StringBuffer toAppend = new StringBuffer(""); public static StringBuffer toSend = new StringBuffer(""); public static JFrame mainFrame = null; public static JTextArea chatText = null; public static JTextField chatLine = null; public static JPanel statusBar = null; public static JLabel statusField = null; public static JTextField statusColor = null; public static ServerSocket hostServer = null; public static Socket socket = null; public static BufferedReader in = null; public static PrintWriter out = null; private static void initGUI() { statusField = new JLabel(); statusField.setText(statusMessages[DISCONNECTED]); statusColor = new JTextField(1); statusColor.setBackground(Color.red); statusColor.setEditable(false); statusBar = new JPanel(new BorderLayout()); statusBar.add(statusColor, BorderLayout.WEST); statusBar.add(statusField, BorderLayout.CENTER); JPanel chatPane = new JPanel(new BorderLayout()); chatText = new JTextArea(10, 20); chatText.setLineWrap(true); chatText.setEditable(false); chatText.setForeground(Color.blue); JScrollPane chatTextPane = new JScrollPane(chatText, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER); chatLine = new JTextField(); chatLine.setEnabled(false); chatLine.addActionListener(new ActionAdapter() {

public void actionPerformed(ActionEvent e) { String s = chatLine.getText(); if (!s.equals("")) { appendToChatBox("OUTGOING: " + s + "\n"); chatLine.selectAll();//IF WANT TO CLEAR DO HERE // Send the string sendString(s); } } }); chatPane.add(chatLine, BorderLayout.SOUTH); chatPane.add(chatTextPane, BorderLayout.CENTER); chatPane.setPreferredSize(new Dimension(200, 200)); JPanel mainPane = new JPanel(new BorderLayout()); mainPane.add(statusBar, BorderLayout.SOUTH); mainPane.add(chatPane, BorderLayout.CENTER); mainFrame = new JFrame("GUI CHAT CLIENT"); mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); mainFrame.setContentPane(mainPane); mainFrame.setSize(mainFrame.getPreferredSize()); mainFrame.pack(); mainFrame.setVisible(true); } private static void changeStatusTS(int newConnectStatus, boolean noError) { if (newConnectStatus != NULL) { connectionStatus = newConnectStatus; } if (noError) { statusString = statusMessages[connectionStatus]; } else { statusString = statusMessages[NULL]; } SwingUtilities.invokeLater(tcpObj); } private static void appendToChatBox(String s) { synchronized (toAppend) { toAppend.append(s); } } private static void sendString(String s) { synchronized (toSend) { toSend.append(s + "\n"); }

} private static void cleanUp() { try { if (hostServer != null) { hostServer.close(); hostServer = null; } } catch (IOException e) { hostServer = null; } try { if (socket != null) { socket.close(); socket = null; } } catch (IOException e) { socket = null; } try { if (in != null) { in.close(); in = null; } } catch (IOException e) { in = null; } if (out != null) { out.close(); out = null; } } public void run() { switch (connectionStatus) { case CONNECTED: chatLine.setEnabled(true); statusColor.setBackground(Color.GREEN); break; case BEGIN_CONNECT: chatLine.setEnabled(false); chatLine.grabFocus(); statusColor.setBackground(Color.ORANGE); break; case DISCONNECTED: chatLine.setEnabled(false); statusColor.setBackground(Color.RED);

break; } statusField.setText(statusString); chatText.append(toAppend.toString()); toAppend.setLength(0); mainFrame.repaint(); } public static void main(String args[]) { String s; initGUI(); while (true) { try { // Poll every ~10 ms Thread.sleep(10); } catch (InterruptedException e) { } switch (connectionStatus) { case BEGIN_CONNECT: try { socket = new Socket(hostIP, port); in = new BufferedReader(new InputStreamReader(socket.getInputStream())); out = new PrintWriter(socket.getOutputStream(), true); changeStatusTS(CONNECTED, true); } catch (IOException e) { cleanUp(); changeStatusTS(DISCONNECTED, false); } break; case CONNECTED: try { if (toSend.length() != 0) { out.print(toSend); out.flush(); toSend.setLength(0); changeStatusTS(NULL, true); } if (in.ready()) { s = in.readLine(); if ((s != null) && (s.length() != 0)) { if (s.equals("*** Bye ***")) { changeStatusTS(DISCONNECTED, true); } else { appendToChatBox("INCOMING: " + s + "\n"); changeStatusTS(NULL, true); } } }

} catch (IOException e) { cleanUp(); changeStatusTS(DISCONNECTED, false); } break; default: break; // do nothing } } } } class ActionAdapter implements ActionListener { public void actionPerformed(ActionEvent e) { } } OUTPUT: C:\Documents and Settings\Student>d: D:\>cd javas D:\javas>set path=D:\Java\jdk1.6\bin D:\javas>javac MultiThreadChatServer.java D:\javas>javac TCPChat.java D:\javas>java MultiThreadChatServer

Вам также может понравиться