RMI Chat

RMI es un mecanismo ofrecido por Java para invocar un método de manera remota. Forma parte del entorno estándar de ejecución de Java y provee de un mecanismo simple para la comunicación de servidores en aplicaciones distribuidas basadas exclusivamente en Java

Codigo de Servidor- Cliente

RmiServidor.java


import java.net.InetAddress;
import java.rmi.*;
import java.rmi.registry.*;
import java.rmi.server.*;
import javax.swing.JFrame;

public class RmiServidor extends UnicastRemoteObject implements InterfazReceptorMensajes {
private static GUIServidor ventana;
private int estePuerto;
private String estaIP;
private Registry registro;

public RmiServidor() throws RemoteException {
try {
// obtener la direccion de este host.
estaIP = (InetAddress.getLocalHost()).toString();
} catch (Exception e) {
throw new RemoteException("No se puede obtener la direccion IP.");
}
estePuerto = 3232; // asignar el puerto que se registra
ventana.anadirEntradas("Conexion establecida por...\nEsta direccion=" + estaIP + ", y puerto=" + estePuerto);
try {
// crear el registro y ligar el nombre y objeto.

registro = LocateRegistry.createRegistry(estePuerto);
registro.rebind("rmiServidor", this);
} catch (RemoteException e) {
throw e;
}}

public void recibirMensaje(String texto) throws RemoteException {
ventana.anadirEntradas(texto);
}

public static void main(String[] args) {
JFrame.setDefaultLookAndFeelDecorated(true);
ventana = new GUIServidor();
ventana.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
try {
new RmiServidor();
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
}
}

RmiCliente.java

import java.rmi.*;
import java.rmi.registry.*;
import javax.swing.*;

import java.awt.*;
import java.awt.event.*;


public class RmiCliente extends JFrame implements ActionListener {
private JTextField cajaEnviar;

private JButton botonEnviar;

private JLabel estado;

private static InterfazReceptorMensajes rmiServidor;

private static Registry registro;

private static String direccionServidor = "192.168.100.1";

private static String puertoServidor = "3232";

public RmiCliente() {
super("Cliente RMI");
getContentPane().setLayout(new BorderLayout());
cajaEnviar = new JTextField();
cajaEnviar.addActionListener(this);
botonEnviar = new JButton("Enviar");
botonEnviar.addActionListener(this);
estado = new JLabel("Estado...");

getContentPane().add(cajaEnviar);
getContentPane().add(botonEnviar, BorderLayout.EAST);
getContentPane().add(estado, BorderLayout.SOUTH);

setSize(300, 100);
setVisible(true);
}

public void actionPerformed(ActionEvent e) {
if (!cajaEnviar.getText().equals("")) {
enviarMensaje(cajaEnviar.getText());
cajaEnviar.setText("");
}
}

private static void conectarseAlServidor() {
try {
// obtener el registro
registro = LocateRegistry.getRegistry(direccionServidor,
(new Integer(puertoServidor)).intValue());
// creando el objeto remoto
rmiServidor = (InterfazReceptorMensajes) (registro
.lookup("rmiServidor"));
} catch (RemoteException e) {
e.printStackTrace();
} catch (NotBoundException e) {
e.printStackTrace();
}
}

private void enviarMensaje(String mensaje) {
estado.setText("Enviando " + mensaje + " a " + direccionServidor + ":"
+ puertoServidor);
try {
// llamando el metodo remoto
rmiServidor.recibirMensaje(mensaje);
estado.setText("El mensaje se ha enviado!!!");
} catch (RemoteException re) {
re.printStackTrace();
}
}

static public void main(String args[]) {
JFrame.setDefaultLookAndFeelDecorated(true);
conectarseAlServidor();
RmiCliente ventana = new RmiCliente();
ventana.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}

4 comentarios:

Anónimo dijo...

como hago correr los dos archivos? :(

Anónimo dijo...

le faltan 2 archivos mas y tengo un error de ip :s

Anónimo dijo...

Hola que tal,muy pleno tu explicacion ... pero no se si me puedes ayudar con una pregunta, si deseo realizar un chat con 2 clientes conectados a un sevidor ????.. como lo hago porfa ayuda.

Anónimo dijo...

es una chafada un plagio, te falta codigo de GUIServidor . .. .. :P

Publicar un comentario