Quisiera saber como usar Multi Hilos con Socket en java, el contexto es el siguiente quiero realizar un Chat con varios clientes ( usuario1,usuario2,usuario3 ...etc) y que cuando yo el servidor envie un mensajes se lo envie solo al usuario1 por ejemplo si eligo esa opcion.
Si elijo enviar un mensaje al usuario2 solo debe llegarle al usuario 2 .
Aqui les dejo un codigo de un chat , pero con un cliente solamente no se como podria agregarlo para varios y que se maneje el contexto que indico lineas arriba
Gracias por todo
Código:
public class Cliente implements Runnable{ private Socket s; private ObjectOutputStream oos; private ObjectInputStream ois; private MainWindow mw; public Cliente(MainWindow mw){ this.mw=mw; } public void run() { try { s=new Socket("192.168.1.80",9991); oos= new ObjectOutputStream(s.getOutputStream()); ois=new ObjectInputStream(s.getInputStream()); mw.getAreaChat().append("Conexion Exitosa Cliente"); this.leerLinea(); } catch (Exception e) { this.close(); e.printStackTrace(); } } public void close(){ try { oos.close(); ois.close(); s.close(); } catch (Exception e) { e.printStackTrace(); } } public void writeLine(String linea){ try { oos.writeObject(linea); } catch (Exception e) { e.printStackTrace(); } } public void leerLinea(){ try { //bucle while(true){ Object aux=ois.readObject(); if(aux!=null && aux instanceof String){ mw.getAreaChat().append("\nServidor dice: " + (String)aux); } Thread.sleep(15); } } catch (Exception e) { e.printStackTrace(); } } }
SERVIDOR
Código:
public class Servidor implements Runnable{ private ServerSocket ss; private Socket s; private ObjectOutputStream oos; private ObjectInputStream ois; private MainWindow mw; public Servidor(MainWindow mw){ this.mw=mw; } public void run() { try { ss=new ServerSocket(9991); s=ss.accept(); oos=new ObjectOutputStream(s.getOutputStream()); ois=new ObjectInputStream(s.getInputStream()); mw.getAreaChat().append("Conexion Exitosa"); //llamamos a leer linesas} this.leerLinea(); } catch (Exception e) { this.closeServer(); e.printStackTrace(); } } public void writeLine(String linea){ try { oos.writeObject(linea); } catch (Exception e) { e.printStackTrace(); } } public void leerLinea(){ try { //bucle while(true){ Object aux=ois.readObject(); if(aux!=null && aux instanceof String){ mw.getAreaChat().append("\nAustin dice: " +(String)aux); } Thread.sleep(15); } } catch (Exception e) { e.printStackTrace(); } } public void closeServer(){ try { oos.close(); ois.close(); s.close(); ss.close(); } catch (Exception e) { e.printStackTrace(); } } }
INTERFAZ SWING
Código:
public class MainWindow extends JFrame implements ActionListener,WindowListener{ private JMenuBar menuBar; private JMenu accion; private JMenuItem conect,create,exit; private Servidor s; private Cliente c; private JTextArea areaChat; public JTextArea getAreaChat() { return areaChat; } private JTextField text; private JButton send; private JScrollPane scroll; public MainWindow(){ super("Chat Niktutos"); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.setSize(400,600); //hacemos que escuche metodos WindowListerne this.addWindowListener(this); this.setComponents(); this.setVisible(true); } public void setComponents(){ menuBar = new JMenuBar(); this.setJMenuBar(menuBar); accion = new JMenu("Acci�n"); menuBar.add(accion); conect = new JMenuItem("Conectar"); conect.addActionListener(this); accion.add(conect); create = new JMenuItem("Crear Servidor"); create.addActionListener(this); accion.add(create); exit = new JMenuItem("Salir"); exit.addActionListener(this); accion.add(exit); this.setLayout(new GridBagLayout()); GridBagConstraints gbc = new GridBagConstraints(); gbc.gridx = 0; gbc.gridy = 0; gbc.gridwidth = 2; gbc.gridheight = 1; gbc.fill = GridBagConstraints.BOTH; gbc.weightx = 1.0; gbc.weighty = 1.0; areaChat = new JTextArea(); scroll = new JScrollPane(areaChat); this.add(scroll,gbc); gbc.gridx=0; gbc.gridy=1; gbc.gridwidth=1; gbc.gridheight=1; gbc.fill = GridBagConstraints.HORIZONTAL; gbc.weightx = 1.0; gbc.weighty = 0.0; text = new JTextField(20); this.add(text,gbc); gbc.gridx=1; gbc.gridy=1; gbc.gridwidth=1; gbc.gridheight=1; gbc.fill = GridBagConstraints.NONE; gbc.weightx = 0.0; gbc.weighty = 0.0; send = new JButton("Enviar"); send.addActionListener(this); this.add(send,gbc); } public void actionPerformed(ActionEvent ae) { if(ae.getSource()==create){ s=new Servidor(this); Thread t=new Thread(s); t.start(); }else if(ae.getSource()==conect){ c=new Cliente(this); Thread t=new Thread(c); t.start(); }else if(ae.getSource()==exit){ this.dispose(); }else if(ae.getSource()==send){ if(s!=null){ s.writeLine(text.getText()); areaChat.append("\n Serv: " + text.getText()); text.setText(""); } if(c!=null){ c.writeLine(text.getText()); areaChat.append("\n Austin : " + text.getText()); text.setText(""); } } } @Override public void windowOpened(WindowEvent e) { // TODO Auto-generated method stub } @Override public void windowClosing(WindowEvent e) { // TODO Auto-generated method stub } @Override public void windowClosed(WindowEvent e) { //si Servidor esta instanciado if(s!=null){ s.closeServer(); } //si Cliente esta instanciado if(c!=null){ c.close(); } } @Override public void windowIconified(WindowEvent e) { // TODO Auto-generated method stub } @Override public void windowDeiconified(WindowEvent e) { // TODO Auto-generated method stub } @Override public void windowActivated(WindowEvent e) { // TODO Auto-generated method stub } @Override public void windowDeactivated(WindowEvent e) { // TODO Auto-generated method stub } }