Download REPORTE DEL PROYECTO DE PROGRAMACION
Document related concepts
no text concepts found
Transcript
REPORTE DEL PROYECTO DE PROGRAMACION ELABORACIÓN DE UN CHAT 1.- Se creo un servidor para poder hacer la comunicación entre varios clientes en la red import java.net.*; import java.io.*; import java.util.*; public class ChatServidor { public ChatServidor() throws IOException { Vector x = new Vector(); //Creamos un servidor ServerSocket server = new ServerSocket(20,2,InetAddress.getByName("192.168.0.9")); while (true) { Socket client = server.accept (); System.out.println("Entro " + client.getInetAddress()); x.add(client.getInetAddress()); Sirvo c = new Sirvo(client,x); c.start (); } } public static void main (String args[]) throws IOException { new ChatServidor(); } } import java.net.*; import java.io.*; import java.util.*; public class Sirvo extends Thread { protected Socket s; protected DataInputStream i; protected DataOutputStream o; Vector y = new Vector(); public Sirvo(Socket s, Vector x) throws IOException { this.s = s; i = new DataInputStream (new BufferedInputStream (s.getInputStream ())); o = new DataOutputStream (new BufferedOutputStream (s.getOutputStream ())); y = x; } protected static Vector handlers = new Vector (); public void run () { String name = s.getInetAddress ().toString (); String Listado=""; try { for (int i=0; i < y.size() ; i++) Listado=Listado+y.get(i)+"\n"; handlers.addElement (this); broadcast ("->" + Listado); while (true) { String msg = i.readUTF (); broadcast (name + " - " + msg); } } catch (IOException ex) { ex.printStackTrace (); } finally { handlers.removeElement (this); y.remove(name); Listado=""; for (int i=0; i < y.size() ; i++) Listado=Listado+y.get(i)+"\n"; broadcast ("<-" + Listado); try { s.close (); } catch (IOException ex) { ex.printStackTrace(); } } } protected static void broadcast (String message) { synchronized (handlers) { Enumeration e = handlers.elements (); while (e.hasMoreElements ()) { Sirvo c = (Sirvo) e.nextElement (); try { synchronized (c.o) { c.o.writeUTF (message); } c.o.flush (); } catch (IOException ex) { c.stop (); } } } } } 2.- Posteriormente se tuvo que crear un código de interfaz para poderse comunicar en un ambiente grafico para cada uno de los clientes que se conecten al servidor. import java.net.*; import java.io.*; import javax.swing.*; import java.awt.*; import java.awt.event.*; /** * creado por alberto leon aparicio */ public class ChatCliente { /** * Constructor */ public ChatCliente() throws IOException { Socket s = new Socket (InetAddress.getByName ("192.168.0.9"), 20); Frame frame = new Interfaz("Chat " + " 192.168.0.9 " + ": " + "20", s.getInputStream (), s.getOutputStream ()); // Frame frame = new Interfaz(); //Center the window Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); Dimension frameSize = frame.getSize(); if (frameSize.height > screenSize.height) { frameSize.height = screenSize.height; } if (frameSize.width > screenSize.width) { frameSize.width = screenSize.width; } frame.setLocation((screenSize.width - frameSize.width)/2, (screenSize.height frameSize.height)/2); frame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }); frame.setVisible(true); } /** * main * param args */ public static void main(String[] args) throws IOException{ try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (Exception e) { e.printStackTrace(); } new ChatCliente(); } } import java.net.*; import java.io.*; import javax.swing.*; import java.awt.*; import java.awt.event.*; import java.util.*; /** *un balance basado en una clase ventana de alto nivel. * */ public class Interfaz extends JFrame implements Runnable{ BorderLayout borderLayout1 = new BorderLayout(); JMenuBar menuBar1 = new JMenuBar(); JMenu menuFile = new JMenu(); JMenuItem menuFileExit = new JMenuItem(); JMenu menuHelp = new JMenu(); JMenuItem menuHelpAbout = new JMenuItem(); JSplitPane jSplitPane1 = new JSplitPane(); JSplitPane jSplitPane2 = new JSplitPane(); JScrollPane jScrollPane1 = new JScrollPane(); JScrollPane jScrollPane2 = new JScrollPane(); JTextArea jTextArea1 = new JTextArea(); JTextArea jTextArea2 = new JTextArea(); JPanel jPanel1 = new JPanel(); JLabel jLabel1 = new JLabel(); JSplitPane jSplitPane3 = new JSplitPane(); JScrollPane jScrollPane3 = new JScrollPane(); JPanel jPanel2 = new JPanel(); TextField input = new TextField(); JTextArea output = new JTextArea(); JButton jButton1 = new JButton(); DataInputStream i; DataOutputStream o; protected Thread escuchar; /** * Construccion de la nueva instancia. */ public Interfaz(String title, InputStream i, OutputStream o) { super(title); this.i = new DataInputStream (new BufferedInputStream (i)); this.o = new DataOutputStream (new BufferedOutputStream (o)); try { jbInit(); } catch (Exception e) { } input.requestFocus (); escuchar = new Thread (this); escuchar.start (); } /**"chat inicioms para proyecto de concurrente" * se inicializan los estados de las instancias */ private void jbInit() throws Exception { this.getContentPane().setLayout(borderLayout1); this.setSize(new Dimension(495, 592)); menuFile.setText("Archivo"); menuFileExit.setText("Salir....."); menuFile.setFont(new Font("Century", 2, 18)); jSplitPane1.setOrientation(JSplitPane.VERTICAL_SPLIT); jTextArea1.setText(""); jTextArea2.setEditable(false); output.setEditable(false); jLabel1.setText("Prog. Concurrente"); jLabel1.setFont(new Font("Algerian", 2, 30)); jButton1.setText("Enviar!.."); menuFile.add(menuFileExit); menuBar1.add(menuFile); menuHelp.add(menuHelpAbout); menuBar1.add(menuHelp); this.setJMenuBar(menuBar1); this.getContentPane().add(jSplitPane1, BorderLayout.CENTER); jSplitPane1.add(jSplitPane2, JSplitPane.BOTTOM); jSplitPane2.add(jScrollPane1, JSplitPane.RIGHT); jScrollPane1.getViewport().add(jTextArea1, null); jScrollPane1.getViewport().add(output, null); jSplitPane2.add(jScrollPane2, JSplitPane.LEFT); jScrollPane2.getViewport().add(jTextArea2, null); jSplitPane1.add(jPanel1, JSplitPane.TOP); jPanel1.add(jLabel1, null); this.getContentPane().add(jSplitPane3, BorderLayout.SOUTH); jSplitPane3.add(jScrollPane3, JSplitPane.BOTTOM); jScrollPane3.getViewport().add(input, null); jSplitPane3.add(jPanel2, JSplitPane.TOP); jPanel2.add(jButton1, null); //---------------------------------------------------------------------menuFileExit.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { fileExit_ActionPerformed(e); } }); //---------------------------------------------------------------------jButton1.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { try { o.writeUTF (input.getText()); o.flush (); System.out.println("Enviando..."); } catch (IOException ex) { ex.printStackTrace(); escuchar.stop (); } input.setText (""); } }); //---------------------------------------------------------------------} public void run () { Vector control = new Vector(); String s; try { while (true) { String line = i.readUTF (); if (line.substring(0,2).equals("->")){ jTextArea2.setText(" \n"); jTextArea2.append(line.substring(2)); } else{ if (line.substring(0,2).equals("<-")){ jTextArea2.setText("\n"); System.out.println("Salio "+line); jTextArea2.append(line.substring(2)); } else output.append(line + "\n"); } } } catch (IOException ex) { ex.printStackTrace (); } finally { escuchar = null; input.hide (); validate (); try { o.close (); } catch (IOException ex) { ex.printStackTrace (); } } } public boolean handleEvent (Event e) { if ((e.target == input) && (e.id == Event.ACTION_EVENT)) { try { o.writeUTF ((String) e.arg); o.flush (); } catch (IOException ex) { ex.printStackTrace(); escuchar.stop (); } input.setText (""); return true; } else if ((e.target == this) && (e.id == Event.WINDOW_DESTROY)) { if (escuchar != null) escuchar.stop (); hide (); return true; } return super.handleEvent (e); } //---------------------------------------------------------------------void fileExit_ActionPerformed(ActionEvent e) { System.exit(0); } } 3.- si uno de los clientes decide desconectarse en el otro le saldrá un mensaje del equipo que salio…