Chat serveur (rooms)
Clientpackage
roomsCl; import java.net.*; import java.awt.*; import java.io.*; import java.awt.event.*; import javax.swing.*; public class Client { BufferedReader in; PrintWriter out; InetAddress addr; Socket socket; String name; int room; Gui g; Client(JFrame f){ g = new Gui(f); } class Gui{ JTextArea serv; JTextField cl; Gui (Frame f){ f.setLayout(new BorderLayout()); serv = new JTextArea(20,10); serv.setEditable(false); serv.setBackground(new Color(230,230,230)); serv.setFont(new Font("SANS_SERIF", Font.BOLD, 14)); cl = new JTextField(30); f.add("Center",new JScrollPane(serv)); f.add("South",cl); cl.addActionListener(new SrvL()); (new Rcv()).start(); } class SrvL implements ActionListener{ public void actionPerformed(ActionEvent e){ try{ String st=cl.getText(); send(st); cl.setText(""); } catch (Exception ex){ System.out.println("exception: "+ex); System.out.println("closing..."); try{ socket.close(); } catch (Exception expt){ System.out.println(expt); } } } } class Rcv extends Thread{ public void run(){ for(;;){ try { sleep(400); } catch (InterruptedException e){} try{ serv.append(in.readLine()+"\n"); serv.setCaretPosition(serv.getDocument().getLength()); } catch (IOException e1){break;} catch(NullPointerException e2) {} // 1-st time before start } System.out.println("thread receive from server closing..."); try{ socket.close(); } catch (Exception expt){ System.out.println(expt); } System.exit(0); } } } public void init()throws IOException{ try{ do{ name = JOptionPane.showInputDialog("Please enter your name"); } while((name == null)|| (name.length()==0)); String server = null; InetAddress addr = InetAddress.getByName(server); System.out.println("addr = " + addr); socket = new Socket(addr, 9080); System.out.println("socket = " + socket); in = new BufferedReader( new InputStreamReader(socket.getInputStream())); // Output is automatically flushed // by PrintWriter: out = new PrintWriter(new BufferedWriter( new OutputStreamWriter(socket.getOutputStream())),true); }catch (Exception e){ System.out.println("exception: "+e); System.out.println("closing..."); try{ socket.close(); }catch (Exception e2){ System.out.println("no server running"); System.exit(5); } } do{ room=-1; try{ room = Integer.parseInt(JOptionPane.showInputDialog("Please enter chat room (0-5)")); } catch (Exception e){} }while ((room<0)||(room>5)); //rooms range out.println(name); //sending name to server out.println(""+room); // sending room to server } void send(String s){ if(s.length()==0){ int quit = JOptionPane.showConfirmDialog(null, "Exit chat"); if(quit == 0) { System.out.println(quit); out.println("END"); System.out.println("closing..."); try{ socket.close(); } catch (Exception expt){ //System.out.println(expt); } System.exit(0); } } else out.println(name+": "+s); } public static void main(String[] args )throws IOException{ JFrame frame =new JFrame(); frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE); Client cl = new Client(frame); cl.init(); frame.setTitle(cl.name+ " room:"+cl.room+ " (empty line to exit)"); frame.setSize(500,300); frame.setVisible(true); } } |
package
roomsSrv; import java.io.*; class Client{ String name; PrintWriter pw; Client(String name, PrintWriter pw){ this.name=name; this.pw=pw; } } public class Clients { Client arr[]; int arr_size; Clients(){ arr = new Client[10]; arr_size=0; } synchronized void addElement(Client out){ if(arr_size==arr.length) { Client temp[]= new Client[arr.length*2]; System.arraycopy(arr, 0, temp, 0, arr_size); arr=temp; } arr[arr_size++]=out; } synchronized void removeElement(Client out){ for(int i=0;i<arr_size;i++){ if(arr[i]==out){ arr[i]=arr[--arr_size]; break; } } } synchronized Client elementAt(int i){ return arr[i]; } synchronized int size(){ return arr_size; } } |
package
roomsSrv; import java.io.*; import java.net.*; class ServeOneClient extends Thread { private Socket socket; private BufferedReader in; Clients clientWt; private PrintWriter out; private int room=-1; private String name; Client cl; public ServeOneClient(Socket s,Clients[] clientAr) throws IOException { socket = s; in = new BufferedReader( new InputStreamReader( socket.getInputStream())); out = new PrintWriter( new BufferedWriter( new OutputStreamWriter( socket.getOutputStream() ) ), true); name = in.readLine(); room = Integer.parseInt(in.readLine()); //System.out.println("room:"+room); clientWt=clientAr[room]; clientWt.addElement((cl = new Client(name,out))); System.out.print("new client appeared "+ name); System.out.println(" in room: " +room+" total clients in the room: " +clientWt.size()); for(int i =0;i< clientWt.size();i++){ clientWt.elementAt(i).pw.print("new client appeared "+ name); clientWt.elementAt(i).pw.println(" in room: " +room+" total clients in the room: " +clientWt.size()); } start(); // Calls run() } public void run() { try { while (true) { String str = in.readLine(); if (str.equals("END")) break; System.out.println("room "+room+":"+str); System.out.println("total number of clients in room: " +room+" ->" +clientWt.size()); for(int i =0;i< clientWt.size();i++){ clientWt.elementAt(i).pw.println(str); } } System.out.println("closing "+ cl.name+ "..."); clientWt.removeElement(cl); System.out.println("total clients in the room " +room+" : " +clientWt.size()); for(int i =0;i< clientWt.size();i++){ clientWt.elementAt(i).pw.println("closing "+ cl.name+ "..."+"total clients in the room " +room+" : " +clientWt.size()); } } catch (IOException e) { } finally { try { socket.close(); } catch(IOException e) {} } } } public class Chat { static final int PORT = 9080; public static void main(String[] args) throws IOException { ServerSocket s = new ServerSocket(PORT); System.out.println("Chat Server Started"); Clients clientAr[]= new Clients[6]; for(int i=0;i<clientAr.length;i++){ clientAr[i]=new Clients(); } try { while(true) { // Blocks until a connection occurs: Socket socket = s.accept(); try { new ServeOneClient(socket,clientAr); } catch(IOException e) { // If it fails, close the socket, // otherwise the thread will close it: socket.close(); } } } finally { s.close(); } } } |