0% found this document useful (0 votes)
57 views

Chat Con Sockets en Java

This document describes a Java application for creating a chat application using sockets. It includes classes for the client, server, thread, and data transfer object. The client and server classes initialize the graphical user interfaces. The thread class handles socket connections and message passing. The data class serializes chat messages between clients. The document provides instructions for running the client, server, and multiple clients to enable chatting between users. It also describes the key classes used to establish connections and transfer chat messages between clients in real-time.

Uploaded by

henry
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
57 views

Chat Con Sockets en Java

This document describes a Java application for creating a chat application using sockets. It includes classes for the client, server, thread, and data transfer object. The client and server classes initialize the graphical user interfaces. The thread class handles socket connections and message passing. The data class serializes chat messages between clients. The document provides instructions for running the client, server, and multiple clients to enable chatting between users. It also describes the key classes used to establish connections and transfer chat messages between clients in real-time.

Uploaded by

henry
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 9

Henry Pérez García

Aplicaciones Distribuidas
Chat con Sockets en Java

https://bitbucket.org/Jenruco/henryperez-mediochat/src/master/ChatSocketsConNick/

¿Cómo usar?
1- Ejecutar el Servidor
2- Ejecutar el primer Cliente e ingresar un “Nick”

3- Ejecutar el segundo Cliente e ingresar un “Nick”


Henry Pérez García
Aplicaciones Distribuidas

4- Ejecutar un n Cliente e ingresar un “Nick”…


5- Seleccionar el usuario con el que se desea chatear

En este caso “pedro” chateará con “henry”.


6- Chatear
Henry Pérez García
Aplicaciones Distribuidas

Clase Cliente
public class Client {

/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
ClientInterface client = new ClientInterface("Chat - Sockets
Java");
client.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}

Clase Servidor
public class Server {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
ServerInterface interfaceServer =
new ServerInterface("Chat - SocketServer Java");

interfaceServer.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}

Clase Hilo
public class Hilo extends Thread {

private ServerInterface serverInterface;


ArrayList<String> listaip = new ArrayList<>();
HashMap<String, String> ipUser=new HashMap<>();

public Hilo(String name, ServerInterface serverInterfaz) {


super(name);
this.serverInterface = serverInterfaz;
}
Henry Pérez García
Aplicaciones Distribuidas

@Override
public void run() {
ServerSocket serverSocket;
try {
serverSocket = new ServerSocket(9999);
Dato receivedMessage;
while (true) {
try {
Socket server = serverSocket.accept();
ObjectInputStream objectInputStream = new
ObjectInputStream(server.getInputStream());
try {
receivedMessage = (Dato)
objectInputStream.readObject();

if
(!receivedMessage.getTexto().equals("online")) {

serverInterface.getMenssages().append("\nIp " +
receivedMessage.getIp() + " de "
+ receivedMessage.getNick() + ": "
+ receivedMessage.getTexto());

Socket enviar_regreso = new


Socket(receivedMessage.getIp(), 9090);
ObjectOutputStream output_envia = new
ObjectOutputStream(enviar_regreso.getOutputStream());
output_envia.writeObject(receivedMessage);
output_envia.close();
enviar_regreso.close();
} else {
InetAddress localizacion =
server.getInetAddress();
String ipRemota =
localizacion.getHostAddress();

listaip.add(ipRemota);
ipUser.put(ipRemota,
receivedMessage.getNick());

receivedMessage.setListaIps(listaip);
receivedMessage.setIpUser(ipUser);
receivedMessage.setIp(ipRemota);
for (String s : listaip) {
System.out.println("Array: " + s);

Socket enviar_regreso = new Socket(s,


9090);
ObjectOutputStream output_envia = new
ObjectOutputStream(enviar_regreso.getOutputStream());

output_envia.writeObject(receivedMessage);
output_envia.close();
enviar_regreso.close();
}
System.out.println("Ip conectada: " +
ipRemota);
}
} catch (ClassNotFoundException ex) {
Henry Pérez García
Aplicaciones Distribuidas

Logger.getLogger(Hilo.class.getName()).log(Level.SEVERE, null, ex);


}

server.close();
} catch (IOException ex) {
System.out.println(ex.getMessage());
}
}
} catch (IOException ex) {
System.out.println(ex.getMessage());
}
}
}

Clase Dato
public class Dato implements Serializable{
private String nick, ip, texto;
private ArrayList<String> listaIps;
private HashMap<String, String> ipUser;

public Dato(String nick, String ip, String texto) {


this.nick = nick;
this.ip = ip;
this.texto = texto;
}

public Dato() {
}

public HashMap<String, String> getIpUser() {


return ipUser;
}

public void setIpUser(HashMap<String, String> ipUser) {


this.ipUser = ipUser;
}

public ArrayList<String> getListaIps() {


return listaIps;
}

public void setListaIps(ArrayList<String> listaIps) {


this.listaIps = listaIps;
}

public String getNick() {


return nick;
}

public void setNick(String nick) {


this.nick = nick;
}

public String getIp() {


return ip;
}

public void setIp(String ip) {


this.ip = ip;
}
Henry Pérez García
Aplicaciones Distribuidas

public String getTexto() {


return texto;
}

public void setTexto(String texto) {


this.texto = texto;
}
}

Clase ClientInterface
class EnvioOnline extends WindowAdapter {
public static String nickpublic="";
@Override
public void windowOpened(WindowEvent e) {
try {
String nombre = JOptionPane.showInputDialog("Nombre: ");
nickpublic=nombre;
Socket misocket = new Socket("192.168.42.6", 9999);
Dato dato = new Dato();
dato.setTexto("online");
dato.setNick(nombre);
ObjectOutputStream objectOutputStream = new
ObjectOutputStream(misocket.getOutputStream());
objectOutputStream.writeObject(dato);
misocket.close();
} catch (IOException ex) {
System.err.println("Fail in WindowOpened " +
ex.getMessage());
}
}
}

public class ClientInterface extends JFrame implements Runnable {

private final JLabel lblTitle, lblClient, lblIp, lblMessage,


lblMessages;
private final JTextField txtMessage, txtClient, txtIp;
private final JTextArea txtMessages;
private final JButton btnSubmit, btnLimpiar;
private final JPanel panel;
private final JComboBox cmbIp;
private Socket socketClient;

public ClientInterface(String title) {

lblTitle = new JLabel("Chat (Cliente)");


lblClient = new JLabel("");
lblIp = new JLabel("Ip chat: ");
lblMessage = new JLabel("Mensaje: ");
lblMessages = new JLabel("-Chat:-");
txtMessage = new JTextField(25);
txtMessages = new JTextArea(10, 25);
txtClient = new JTextField(25);
txtIp = new JTextField(25);
cmbIp = new JComboBox();

btnSubmit = new JButton("Enviar");


btnLimpiar = new JButton("Limpiar");
Henry Pérez García
Aplicaciones Distribuidas
btnSubmit.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
try {
//System.out.println("Hola funciona");
socketClient = new Socket("192.168.42.6", 9999);
try (ObjectOutputStream objectOutputStream = new
ObjectOutputStream(socketClient.getOutputStream())) {
Dato dato = new
Dato(nickpublic,ipUserSelect.get(cmbIp.getSelectedItem().toString()) ,
txtMessage.getText());
txtMessages.append("\n Yo:" +
txtMessage.getText());
objectOutputStream.writeObject(dato);
objectOutputStream.close();
}
socketClient.close();
} catch (IOException ex) {
txtMessages.setText(txtMessages.getText() + "\n" +
txtMessage.getText() + " - Message not sent: " + ex.getMessage());
System.out.println(ex.getMessage());
}
}
});

panel = new JPanel();


panel.add(lblTitle);
panel.add(cmbIp);
panel.add(txtMessages);
panel.add(lblMessage);
panel.add(txtMessage);
panel.add(btnSubmit);
panel.add(btnLimpiar);
panel.add(lblClient);

addWindowListener(new EnvioOnline());
this.setBounds(80, 35, 320, 410);
this.add(panel);
this.setVisible(true);
this.setTitle(title);

Thread hilo = new Thread(this);


hilo.start();

HashMap<String, String> ipUser = new HashMap<>();


HashMap<String, String> ipUserSelect = new HashMap<>();
@Override
public void run() {
ServerSocket serverSocket;

Socket cliente;
try {
serverSocket = new ServerSocket(9090);
//System.out.println("Ya creó el ServerSocket");
Dato datos;
while (true) {
try {
cliente = serverSocket.accept();
Henry Pérez García
Aplicaciones Distribuidas
ObjectInputStream objectInputStream = new
ObjectInputStream(cliente.getInputStream());
try {
datos = (Dato) objectInputStream.readObject();
if (!datos.getTexto().equals("online")) {
txtMessages.append("\n" + datos.getNick()
+ ": " + datos.getTexto());
} else {

ArrayList<String> lista_ips = new


ArrayList<String>();
ipUser=datos.getIpUser();
lista_ips = datos.getListaIps();
cmbIp.removeAllItems();
for (String ip : lista_ips) {

if(!nickpublic.equals(ipUser.get(ip)))
cmbIp.addItem(ipUser.get(ip));
ipUserSelect.put(ipUser.get(ip), ip);
}
//lblClient.setText(""+nickpublic+"");
}
} catch (ClassNotFoundException ex) {
ex.getMessage();
}
} catch (IOException ex) {
System.out.println(ex.getMessage());
}
}
} catch (IOException ex) {
System.out.println(ex.getMessage());
}
}
}

Clase ServerInterface
public final class ServerInterface extends JFrame {
private final JLabel lblTitle, lblMessages; /*, lblMessage*/
//private final JTextField txtClient, txtIp; //txtMessage
private final JTextArea txtMessages;
private final JButton btnLimpiar; //btnSubmit,
private final JPanel panel;
//private final Thread myThread;
private Hilo hilo;

public JTextArea getMenssages(){


return txtMessages;
}

public ServerInterface(String title){


lblTitle = new JLabel("Chat (Servidor)");
lblMessages = new JLabel ("Chat: ");
txtMessages = new JTextArea (10, 25);
btnLimpiar = new JButton("Limpiar");
panel = new JPanel();
panel.add(lblTitle);
panel.add(lblMessages); panel.add(txtMessages);
panel.add(btnLimpiar);
this.setBounds(800, 350, 320, 410);
this.add(panel);
this.setVisible(true);
Henry Pérez García
Aplicaciones Distribuidas
this.setTitle(title);
hilo = new Hilo ("Hilo", this);
hilo.start();
}
}

You might also like