Foros del Web » Programación para mayores de 30 ;) » Java »

Chat Multihilo Socket Multi hilo Java

Estas en el tema de Chat Multihilo Socket Multi hilo Java en el foro de Java en Foros del Web. Hola 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 ...
  #1 (permalink)  
Antiguo 16/06/2011, 09:36
 
Fecha de Ingreso: marzo-2008
Mensajes: 37
Antigüedad: 16 años, 1 mes
Puntos: 0
Chat Multihilo Socket Multi hilo Java

Hola

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
		
	}

}
  #2 (permalink)  
Antiguo 16/06/2011, 11:05
Avatar de jahepi
Colaborador
 
Fecha de Ingreso: diciembre-2004
Ubicación: Querétaro
Mensajes: 1.124
Antigüedad: 19 años, 4 meses
Puntos: 43
Respuesta: Chat Multihilo Socket Multi hilo Java

Hola HalleyR !

Actualmente el hilo servidor está a la espera de una sóla conexión, lo que debes hacer es crear un nuevo hilo por cada conexión aceptada dentro del hilo servidor.

Crea una nueva clase Cliente que extienda la clase Thread o implemente la interfaz Runnable, deberás instanciarla dentro del hilo servidor por cada conexión establecida, finalmente cuando haya entrada de datos en algún cliente lo tendrás que notificar a los demás clientes conectados.

Un saludote !
__________________
Una contraseña es como la ropa interior. No deberías dejarlas afuera a la vista de otras personas, deberías cambiarla regularmente, y ni se te ocurra prestarla a extraños.
  #3 (permalink)  
Antiguo 16/06/2011, 11:14
Avatar de pyanqn  
Fecha de Ingreso: noviembre-2005
Mensajes: 331
Antigüedad: 18 años, 5 meses
Puntos: 8
Respuesta: Chat Multihilo Socket Multi hilo Java

Esta simple, debes mantener una lista o map con cliente, sockt. de eso modo cuando quieras comunicarte con solo una persona, le mandas a travez del socket con el cual lo atendiste

saludos
__________________
Software Neuquén
  #4 (permalink)  
Antiguo 16/06/2011, 11:30
Avatar de jahepi
Colaborador
 
Fecha de Ingreso: diciembre-2004
Ubicación: Querétaro
Mensajes: 1.124
Antigüedad: 19 años, 4 meses
Puntos: 43
Respuesta: Chat Multihilo Socket Multi hilo Java

Hola de nuevo HalleyR !

Como no hay nada mejor que un tutorial acompañado de un ejemplo busqué y encontré uno bastante bueno y el código está clarísimo, de hecho el autor del mismo chuidiang es miembro de esta comunidad y participa en estos foros.

Te dejo el enlace para que le eches un vistazo:
http://www.chuidiang.com/java/socket...cket_hilos.php

Un saludo y suerte !
__________________
Una contraseña es como la ropa interior. No deberías dejarlas afuera a la vista de otras personas, deberías cambiarla regularmente, y ni se te ocurra prestarla a extraños.
  #5 (permalink)  
Antiguo 20/06/2011, 12:00
 
Fecha de Ingreso: marzo-2008
Mensajes: 37
Antigüedad: 16 años, 1 mes
Puntos: 0
Respuesta: Chat Multihilo Socket Multi hilo Java

Hola jahepi , gracias por el link lo visitare y tratare de implementarlo . Si me sale bien pongo el codigo para que nos sirva a todos.

Saludos

Etiquetas: hilos, multihilos, socket
Atención: Estás leyendo un tema que no tiene actividad desde hace más de 6 MESES, te recomendamos abrir un Nuevo tema en lugar de responder al actual.
Respuesta




La zona horaria es GMT -6. Ahora son las 18:26.