Foro de elhacker.net

Programación => Java => Mensaje iniciado por: Debci en 26 Agosto 2009, 12:21 pm



Título: Chat en Java [Sockets]
Publicado por: Debci en 26 Agosto 2009, 12:21 pm
Hola amigos, les dejo este codigo:
Con el podrán hacer un chat en java simple usando este como base.

Cliente
Código
  1. /*
  2.  * To change this template, choose Tools | Templates
  3.  * and open the template in the editor.
  4.  */
  5.  
  6. package sockets;
  7.  
  8. /**
  9.  *
  10.  * @author debci
  11.  */
  12. import java.io.*;
  13.  
  14. import java.net.*;
  15.  
  16. class Cliente {
  17.  
  18. static final String HOST = "localhost";
  19.  
  20. static final int PUERTO=5000;
  21.  
  22. public Cliente( ) {
  23.  
  24. try{
  25.  
  26. Socket skCliente = new Socket( HOST , PUERTO );
  27.  
  28. InputStream aux = skCliente.getInputStream();
  29.  
  30. DataInputStream flujo = new DataInputStream( aux );
  31.  
  32. System.out.println( flujo.readUTF() );
  33.  
  34. skCliente.close();
  35.  
  36. } catch( Exception e ) {
  37.  
  38. System.out.println( e.getMessage() );
  39.  
  40. }
  41.  
  42. }
  43.  
  44. public static void main( String[] arg ) {
  45.  
  46. new Cliente();
  47.  
  48. }
  49.  
  50. }
  51.  

Servidor

Código
  1. /*
  2.  * To change this template, choose Tools | Templates
  3.  * and open the template in the editor.
  4.  */
  5.  
  6. package sockets;
  7.  
  8. /**
  9.  *
  10.  * @author debci
  11.  */
  12. import java.io.*;
  13.  
  14. import java.net.*;
  15.  
  16. class Cliente {
  17.  
  18. static final String HOST = "localhost";
  19.  
  20. static final int PUERTO=5000;
  21.  
  22. public Cliente( ) {
  23.  
  24. try{
  25.  
  26. Socket skCliente = new Socket( HOST , PUERTO );
  27.  
  28. InputStream aux = skCliente.getInputStream();
  29.  
  30. DataInputStream flujo = new DataInputStream( aux );
  31.  
  32. System.out.println( flujo.readUTF() );
  33.  
  34. skCliente.close();
  35.  
  36. } catch( Exception e ) {
  37.  
  38. System.out.println( e.getMessage() );
  39.  
  40. }
  41.  
  42. }
  43.  
  44. public static void main( String[] arg ) {
  45.  
  46. new Cliente();
  47.  
  48. }
  49.  
  50. }
  51.  

Este servidor solo atiende 3 clientes, pero pueden modificarlo.

Aprovecho para preguntar: ¿como podria hacer para enviar del cliente als ervidor y no del servidor al cliente?

Saludos


Título: Re: Chat en Java [Sockets]
Publicado por: Casidiablo en 27 Agosto 2009, 19:01 pm
Ummm... pero ambas clases se llaman igual  :-\


Título: Re: Chat en Java [Sockets]
Publicado por: egyware en 27 Agosto 2009, 19:26 pm
Yo tenia un chat, tengo solo el Class, si alguien me recomienda un descompilador lo descompilo y lo posteo para que lo vean
(Que no sea el JCavaj que ya no confio en esa cosa)