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

ChatClient.java ChatServer.java Connection.java Hosts.txt

Estas en el tema de ChatClient.java ChatServer.java Connection.java Hosts.txt en el foro de Java en Foros del Web. Muchachos, yo tengo estos 3 o 4 códigos.... Yo soy un principiante pero un amigo me los pasó estos códigos...... compilan y todo,,,,pero no entiendo ...
  #1 (permalink)  
Antiguo 22/12/2008, 20:07
 
Fecha de Ingreso: septiembre-2008
Mensajes: 32
Antigüedad: 15 años, 8 meses
Puntos: 0
ChatClient.java ChatServer.java Connection.java Hosts.txt

Muchachos, yo tengo estos 3 o 4 códigos.... Yo soy un principiante pero un amigo me los pasó estos códigos...... compilan y todo,,,,pero no entiendo bien cómo podría hacer para que me pueda mandar mensajes entre dos computadoras....

Primero, lo pienso probar entre dos computadoras que tengo acá en casa, pero no entiendo cómo hacerlo, alguien que me ayude!!

Tengo wireless, no sé si tiene algo que ver...


Saludos Genios!



Muchas gracias...

Les dejo los.....

Códigos......... unos entran acá, los otros los pongo en otro comentario, No es doble-post, NO ME ENTRAN!!!

GRACIAS!!
-------------------------------------------------------------------------------------------------------
ChatClient.java

Código:
import java.awt.*;
import java.awt.event.*;
import java.net.*;
import java.io.*;

public class ChatClient {

  private Socket connection = null;
  private BufferedReader serverIn = null;
  private PrintStream serverOut = null;

  private TextArea output;
  private TextField input;
  private Button sendButton;
  private Button quitButton;
  private Frame frame;
  private Choice usernames;
  private Dialog aboutDialog;

  public ChatClient() {
    output = new TextArea(10,50);
    input = new TextField(50);
    sendButton = new Button("Send");
    quitButton = new Button("Quit");
    usernames = new Choice();
    usernames.add("Bryan Basham");
    usernames.add("Grand Poobah");
    usernames.add("Java Geek");
  }

  public void launchFrame() {
    frame = new Frame("Chat Room");

    // Use the Border Layout for the frame
    frame.setLayout(new BorderLayout());

    frame.add(output, BorderLayout.WEST);
    frame.add(input, BorderLayout.SOUTH);

    // Create the button panel
    Panel p1 = new Panel(); 
    p1.setLayout(new GridLayout(3,1));
    p1.add(sendButton);
    p1.add(quitButton);
    p1.add(usernames);

    // Add the button panel to the center
    frame.add(p1, BorderLayout.CENTER);

    // Create menu bar and File menu
    MenuBar mb = new MenuBar();
    Menu file = new Menu("File");
    MenuItem quitMenuItem = new MenuItem("Quit");
    quitMenuItem.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent e) {
        exit();
      }
    });
    file.add(quitMenuItem);
    mb.add(file);
    frame.setMenuBar(mb);

    // Add Help menu to menu bar
    Menu help = new Menu("Help");
    MenuItem aboutMenuItem = new MenuItem("About");
    aboutMenuItem.addActionListener(new AboutHandler());
    help.add(aboutMenuItem);
    mb.setHelpMenu(help);

    // Attach listener to the appropriate components
    sendButton.addActionListener(new SendHandler());
    input.addActionListener(new SendHandler());
    frame.addWindowListener(new CloseHandler());
    quitButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
          System.exit(0);
        }
    });

    frame.pack();
    frame.setVisible(true);

    doConnect();
  }

  private void doConnect() {
    // Initialize server IP and port information
    String serverIP = System.getProperty("serverIP", "127.0.0.1");
    String serverPort = System.getProperty("serverPort", "2000");

    try {
      // Create the connection to the chat server
      connection = new Socket(serverIP, Integer.parseInt(serverPort));

      // Prepare the input stream and store it in an instance variable
      InputStream is = connection.getInputStream();
      InputStreamReader isr = new InputStreamReader(is);
      serverIn = new BufferedReader(isr);

      // Prepare the output stream and store it in an instance variable
      serverOut = new PrintStream(connection.getOutputStream());

      // Launch the reader thread
      Thread t = new Thread(new RemoteReader());
      t.start();

    } catch (Exception e) {
      System.err.println("Unable to connect to server!");
      e.printStackTrace();
    }
  }

  private class SendHandler implements ActionListener {
    public void actionPerformed(ActionEvent e) {
      String text = input.getText();
      text = usernames.getSelectedItem() + ": " + text + "\n";
      serverOut.print(text);
      input.setText("");
    }
  }

  private class CloseHandler extends WindowAdapter {
    public void windowClosing(WindowEvent e) {
      exit();
    }
  }

  private void exit() {
    try {
      connection.close();
    } catch (Exception e) {
      System.err.println("Error while shutting down the server connection.");
    }
    System.exit(0);
  }

  private class AboutHandler implements ActionListener {
    public void actionPerformed(ActionEvent e) {
      // Create the aboutDialog when it is requested
      if ( aboutDialog == null ) {
        aboutDialog = new AboutDialog(frame, "About", true);
      }
      aboutDialog.setVisible(true);
    }
  }

  private class AboutDialog extends Dialog implements ActionListener  {
    public AboutDialog(Frame parent, String title, boolean modal) {
      super(parent,title,modal);
      add(new Label("The ChatClient is a neat tool that allows you to talk " +
                  "to other ChatClients via a ChatServer"),BorderLayout.NORTH);
      Button b = new Button("OK");
      add(b,BorderLayout.SOUTH);
      b.addActionListener(this);
      pack();
    }
    // Hide the dialog box when the OK button is pushed
    public void actionPerformed(ActionEvent e) {
      setVisible(false);
    }
  }

  private class RemoteReader implements Runnable {
    public void run() {
      try {
        while ( true ) {
          String nextLine = serverIn.readLine();
          output.append(nextLine + "\n");
        }
      } catch (Exception e) {
        System.err.println("Error while reading from server.");
        e.printStackTrace();
      }
    }
  }

  public static void main(String[] args) {
    ChatClient c = new ChatClient();
    c.launchFrame();
  }
}
  #2 (permalink)  
Antiguo 22/12/2008, 20:08
 
Fecha de Ingreso: septiembre-2008
Mensajes: 32
Antigüedad: 15 años, 8 meses
Puntos: 0
Respuesta: ChatClient.java ChatServer.java Connection.java Hosts.txt

ChatServer.java

Código:
import java.io.*;
import java.net.*;
import java.util.*;
import java.applet.*;

public class ChatServer {

  public static void main(String[] args) {
    ChatServer cs = new ChatServer();
    cs.go();
  }

  public final static int DEFAULT_PORT = 2000;
  public final static int DEFAULT_MAX_BACKLOG = 5;
  public final static int DEFAULT_MAX_CONNECTIONS = 20;
  public final static String DEFAULT_HOST_FILE = "hosts.txt";
  public final static String DEFAULT_SOUND_FILE = "file:gong.au";
  public final static String MAGIC = "Yippy Skippy";

  private String magic = MAGIC;

  private int port = DEFAULT_PORT;
  private int backlog = DEFAULT_MAX_BACKLOG;
  private int numConnections = 0;
  private int maxConnections = DEFAULT_MAX_CONNECTIONS;
  private String hostfile = DEFAULT_HOST_FILE;
  private String soundfile = DEFAULT_SOUND_FILE;
  private List<Connection> connections = null;
  private AudioClip connectSound = null;
  private Map<String,String> hostToStudentMap = null;

  //
  // Methods for the Connection class
  //

  String getMagicPassphrase() {
    return magic;
  }

  String getStudentName(String host) {
    return hostToStudentMap.get(host);
  }

  void sendToAllClients(String message) {
    for ( Connection c : connections ) {
      c.sendMessage(message);
    }
  }

  void playMagicSound() {
    if ( connectSound != null ) {
      connectSound.play();
    }
  }

  synchronized void closeConnection(Connection connection) {
    connections.remove(connection);
    numConnections--;
    notify();
  }

  //
  // Private methods
  //

  private void go() {
    String portString = System.getProperty("port");
    if (portString != null) port = Integer.parseInt(portString);
    this.port = port;

    String backlogString = System.getProperty("backlog");
    if (backlogString != null) backlog = Integer.parseInt(backlogString);

    String hostFileString = System.getProperty("hostfile");
    if (hostFileString != null) hostfile = hostFileString;

    String soundFileString = System.getProperty("soundfile");
    if (soundFileString != null) soundfile = soundFileString;

    String magicString = System.getProperty("magic");
    if (magicString != null) magic = magicString;

    String connections = System.getProperty("connections");
    if (connections != null) maxConnections = Integer.parseInt(connections);

    this.connections = new ArrayList<Connection>(maxConnections);
    this.hostToStudentMap = new HashMap<String,String>(15);

    System.out.println("Server settings:\n\tPort="+port+"\n\tMax Backlog="+
                       backlog+"\n\tMax Connections="+maxConnections+
		       "\n\tHost File="+hostfile+"\n\tSound File="+soundfile);

    createHostList();

    try {
      URL sound = new URL(soundfile);
      connectSound = Applet.newAudioClip(sound);
    } catch(Exception e) {
      e.printStackTrace();
    }

    // Begin the processing cycle
    processRequests();
  }

  private void createHostList() {
    File hostFile = new File(hostfile);
    try {
      System.out.println("Attempting to read hostfile hosts.txt: ");
      FileInputStream fis = new FileInputStream(hostFile);
      InputStreamReader isr = new InputStreamReader(fis);
      BufferedReader br = new BufferedReader(isr);
      String aLine = null;
      while((aLine = br.readLine()) != null) {
	int spaceIndex = aLine.indexOf(' ');
	if (spaceIndex == -1) {
	  System.out.println("Invalid line in host file: "+aLine);
	  continue;
	}
	String host = aLine.substring(0,spaceIndex);
	String student = aLine.substring(spaceIndex+1);
	System.out.println("Read: "+student+"@"+host);
	hostToStudentMap.put(host,student);
      }
    } catch(Exception e) {
      e.printStackTrace();
    }
  }          

  private void processRequests() {
    ServerSocket serverSocket = null;
    Socket communicationSocket;    

    try {
      System.out.println("Attempting to start server...");
      serverSocket = new ServerSocket(port,backlog);
    } catch (IOException e) { 
      System.out.println("Error starting server: Could not open port "+port);
      e.printStackTrace();
      System.exit(-1);
    }
    System.out.println ("Started server on port "+port);

    // Run the listen/accept loop forever
    while (true) {
      try {
        // Wait here and listen for a connection
        communicationSocket = serverSocket.accept();
        handleConnection(communicationSocket);
      } catch (Exception e) { 
        System.out.println("Unable to spawn child socket.");
        e.printStackTrace();
      }
    }
  }

  private synchronized void handleConnection(Socket connection) {
    while (numConnections == maxConnections) {
      try {
	wait();
      } catch(Exception e) { 
	e.printStackTrace();
      }
    }
    numConnections++;
    Connection con = new Connection(this, connection);
    Thread t = new Thread(con);
    t.start();
    connections.add(con);
  }
}
Connection.java


Código:
import java.io.*;
import java.net.*;

class Connection implements Runnable {

  ChatServer server = null;
  private Socket communicationSocket = null;
  private OutputStreamWriter out = null;
  private BufferedReader in = null;

  public Connection(ChatServer server, Socket s) {
    this.server = server;
    this.communicationSocket = s;
  }       

  public void sendMessage(String message) {
    try {
      out.write(message);
      out.flush();
    } catch(Exception e) {
      e.printStackTrace();
    }
  }

  public void run() {
    OutputStream socketOutput = null;
    InputStream socketInput = null;
    String magic = server.getMagicPassphrase();

    try {
      socketOutput = communicationSocket.getOutputStream();
      out = new OutputStreamWriter(socketOutput);
      socketInput = communicationSocket.getInputStream();
      in = new BufferedReader(new InputStreamReader(socketInput));

        
      InetAddress address = communicationSocket.getInetAddress();
      String hostname = address.getHostName();

      String welcome = 
	"Connection made from host: "+hostname+"\nEverybody say hello";
      String student = server.getStudentName(hostname);
      if (student != null) welcome += " to "+student;
      welcome+="!\n";
      server.sendToAllClients(welcome);
      System.out.println("Connection made "+student+"@"+hostname);
      sendMessage("Welcome "+student+" the passphrase is "+magic+"\n");
      String input = null;

      while ((input = in.readLine()) != null) {
	if (input.indexOf(magic) != -1) {
	  server.playMagicSound();
	  sendMessage("Congratulations "+student+" you sent the passphrase!\n");
	  System.out.println(student+" sent the passphrase!");
	} else {
	  server.sendToAllClients(input+"\n");
	}
      }
    } catch(Exception e) {
      e.printStackTrace(System.err);
    } finally {
      try {
	if (in != null) in.close();
	if (out != null) out.close();
	communicationSocket.close();
      }  catch(Exception e) {
	e.printStackTrace();
      }
      server.closeConnection(this);
    }
  }
}

hosts.txt


Código:
localhost Frank
192.168.1.100 Frank
192.168.1.102 Emily
-------------------------------------------------------------------------------------------------------
  #3 (permalink)  
Antiguo 24/12/2008, 13:50
 
Fecha de Ingreso: septiembre-2008
Mensajes: 32
Antigüedad: 15 años, 8 meses
Puntos: 0
Respuesta: ChatClient.java ChatServer.java Connection.java Hosts.txt

Ayuuuuuuuda!!!

muchas gracias
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 11:06.