Java Chat - How to client can listen continuously from the server
I'm working on a university project were I was asked to create a java chat
using sockets and other java features. I have managed to complete
basically the whole assignment (but the GUI part, and that's what I'm
working on now) and I'm having issues when I want the client to
continuously listen to the server, I cannot make all the clients to
receive message from the server (Like a broadcast feature). So if I want
the server to send a message to the clients who are online, they do not
get the message, so the clients are not Listening to the server all time,
and that's where I am stuck. Below my code, so do you have any idea how I
can program this or do you have any suggestion(s)?
You may ignore the comments in Spanish, those are my notes about the code
itself.
Client Classes /* * To change this template, choose Tools | Templates *
and open the template in the editor. */ package vmatesclientv2;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Inet4Address;
import java.net.Socket;
import javax.swing.JOptionPane;
/**
*
* @author murillke
*/
public class Client {
private Socket client;
private ObjectOutputStream out;
private ObjectInputStream in;
private BufferedReader In;
private String serverIP;
private String nombre;
private String email;
private String MSG;
public static int user_ID;
public static int room_ID;
public static boolean admin = false;
public Client() throws IOException {
connectToServer();
startStreams();
new ListenServer(client, in, out, In).start();
}
private void connectToServer() throws IOException {
serverIP = "127.0.0.1";
System.out.println("Iniciando coneccion con el servidor");
client = new Socket(serverIP, 28001);
System.out.println("Conectado con el servidor");
}
private void startStreams() throws IOException {
out = new ObjectOutputStream(client.getOutputStream());
in = new ObjectInputStream(client.getInputStream());
In = new BufferedReader(new
InputStreamReader(client.getInputStream()));
}
// Formato de mensaje:"REGISTER_TYPE"+" "+"Name"+" "+"email"+"
"+"USER_ID"+" "+"ROOM_ID"+"MSG";
public void menu() {
// Listen listen = new Listen(socket);//PREGUNTAR AL PROFESOR COMO
HACE EL CLIENTE PARA RECIBIR LOS MENSAJES
// listen.start();
int tipo = Integer.parseInt(JOptionPane.showInputDialog("Client "
+ admin
+ "\n 1) REGISTER_REQUEST"
+ "\n 2) NEW_ROOM"
+ "\n 3) JOIN_ROOM"
+ "\n 4) SEND_MSG"
+ "\n 5) REMOVE_MATE"
+ "\n 6) FILE_TRANSFER"));
switch (tipo) {
case (1):
REGISTER_REQUEST();
menu();
break;
case (2):
NEW_ROOM();
menu();
break;
case (3):
room_ID =
Integer.parseInt(JOptionPane.showInputDialog("Room ID"));
JOIN_ROOM("Kevin", "kevin@test.com", room_ID);
break;
case (4):
SEND_MSG(JOptionPane.showInputDialog("Mensaje"));
menu();
break;
case (5):
String removeValue = JOptionPane.showInputDialog("removal
criteria (NICK/ID)");
REMOVE_MATE(removeValue);
menu();
break;
case (6):
break;
}
}
public void REGISTER_REQUEST() {
nombre = "Georgie";
email = "email@test.com";
try {
String text = "REGISTER_REQUEST" + " " + nombre + " " + email
+ " " + "null" + " " + "null" + " " + "null";
out.writeUTF(text);
out.flush();
} catch (IOException ex) {
}
}
public void NEW_ROOM() {
nombre = "Georgie";
email = "email@test.com";
try {
String text = "NEW_ROOM" + " " + nombre + " " + email + " " +
"null" + " " + "null" + " " + "null";
out.writeUTF(text);
out.flush();
admin = true;
} catch (IOException ex) {
}
}
// Formato de mensaje:"REQUEST_TYPE"+" "+"Name"+" "+"email"+"
"+"USER_ID"+" "+"ROOM_ID"+"MSG";
public void JOIN_ROOM(String Nombre, String Email, int ROOM_ID) {
try {
String text = "JOIN_ROOM" + " " + Nombre + " " + Email + " " +
"null" + " " + ROOM_ID + " " + "null";
out.writeUTF(text);
out.flush();
} catch (IOException ex) {
}
}
public void REMOVE_MATE(String removeValue) {
try {
if (admin == true) {
String text = "REMOVE_MATE" + " " + removeValue + " " +
"null" + " " + "null" + " " + room_ID + " " + "null";
out.writeUTF(text);
out.flush();
} else {
System.out.println("No puede remover usuarios");
}
} catch (IOException ex) {
}
}
public void SEND_MSG(String msg) {
System.out.println("" + room_ID);
System.out.println("Enviando mensaje");
try {
String text = "SEND_MSG" + " " + "null" + " " + "null" + " " +
user_ID + " " + room_ID + " " + msg;
System.out.println("Enviando: ***" + text + "***");
out.writeUTF(text);
out.flush();
System.out.println("Mensaje enviado");
} catch (IOException ex) {
}
}
public void FILE_TRANSFER(String msg) {
try {
String text = "FILE_TRANSFER" + " " + "null" + " " + "null" +
" " + user_ID + " " + room_ID + " " + msg;
String path = JOptionPane.showInputDialog("Ingrese el path del
archivo a enviar: ");
String userToSend = JOptionPane.showInputDialog("Ingrese
usuario al que desee enviar el archivo: ");
out.writeUTF(text);
out.flush();
} catch (IOException ex) {
}
}
}//FIN DE CLASE
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package vmatesclientv2;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author murillke
*/
public class ListenServer extends Thread {
private Socket client;
private ObjectInputStream in;
private ObjectOutputStream out;
private BufferedReader In;
// private int ID;
// private int room_ID;
// private boolean admin = false;
public ListenServer(Socket client, ObjectInputStream in,
ObjectOutputStream out, BufferedReader In) {
this.client = client;
this.in = in;
this.out = out;
this.In = In;
}
@Override
public void run() {
DataInputStream IN = null;
try {
IN = new DataInputStream(client.getInputStream());
while (true) {
String data = "";
try {
// data =in.readUTF();
data = IN.readUTF();
System.out.println("Recibido: " + data);
} catch (IOException ex) {
Logger.getLogger(ListenServer.class.getName()).log(Level.SEVERE,
null, ex);
}
String[] msg_parts = data.split(" ", 3);
String msg_type = msg_parts[0];
switch (msg_type) {
case "MSG":
System.out.println(msg_parts[0]);
System.out.println(msg_parts[1]);
break;
case "ROOM_&_ID":
System.out.println("ROOM_ID & User_ID recibido");
if (!"null".equals(msg_parts[1])) {
Client.room_ID = Integer.parseInt(msg_parts[1]);
}
Client.user_ID = Integer.parseInt(msg_parts[2]);
System.out.println(Client.room_ID);
System.out.println(Client.user_ID);
break;
case "SET_TO_ADMIN":
System.out.println("This Client is now ADMIN");
Client.admin = true;
break;
}
}
} catch (IOException ex) {
Logger.getLogger(ListenServer.class.getName()).log(Level.SEVERE,
null, ex);
} finally {
try {
IN.close();
} catch (IOException ex) {
Logger.getLogger(ListenServer.class.getName()).log(Level.SEVERE,
null, ex);
}
}
}
}
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package vmatesclientv2;
import java.io.IOException;
/**
*
* @author murillke
*/
public class VMatesClientV2 {
/**
* @param args the command line arguments
*/
public static void main(String[] args) throws IOException {
// TODO code application logic here
Client client = new Client();
client.menu();
}
}
Server Classes
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package vmatesserver;
/**
*
* @author murillke
*/
public class Celda {
private clientThreadServer info;
private Celda next;
private Celda previous;
public Celda getPrevious() {
return previous;
}
public void setPrevious(Celda previous) {
this.previous = previous;
}
public Celda(clientThreadServer info) {
this.info = info;
}
public clientThreadServer getInfo() {
return info;
}
public void setInfo(clientThreadServer info) {
this.info = info;
}
public Celda getNext() {
return next;
}
public void setNext(Celda next) {
this.next = next;
}
}
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package vmatesserver;
/**
*
* @author murillke
*/
public class Lista {
public Celda cabeza;
public Lista() {
cabeza = null;
}
public void inserta(clientThreadServer client) {
if (cabeza == null) { // si la lista está vacia
cabeza = new Celda(client);
} else if (client.getId() < cabeza.getInfo().getId()) { // si
debo insertar a la izquierda de cabeza
Celda aux = new Celda(client);
aux.setNext(cabeza);
cabeza = aux;
} else if (cabeza.getNext() == null) { // si sòlo tiene uno y
debo insertar a la derecha
Celda aux = new Celda(client);
cabeza.setNext(aux);
} else { // hay màs de uno y debemos insertar en medio o al final
Celda actual = cabeza;
while (actual.getNext() != null
&& actual.getNext().getInfo().getId() < client.getId()) {
actual = actual.getNext();
}
Celda aux = new Celda(client);
aux.setNext(actual.getNext());
actual.setNext(aux);
}
}
public boolean existe(int id) {
Celda aux = cabeza;
while (aux != null && aux.getInfo().getId() < id) {
aux = aux.getNext();
}
return (aux != null && aux.getInfo().getId() == id);
}
public clientThreadServer recupera(int id) {
Celda aux = cabeza;
while (aux != null && aux.getInfo().getId() < id) {
aux = aux.getNext();
}
if (aux != null && aux.getInfo().getId() == id) {
return aux.getInfo();
} else {
return null;
}
}
// public clientThreadServer recupera() {
// Celda aux = cabeza;
// while (aux != null) {
// return aux.getInfo();
// aux = aux.getNext();
// }
//
// }
public void elimina(int id) {
Celda aux = cabeza; //se fija el auxiliar como la cabeza
if (aux.getInfo().getId() == id) { //Si id ingresado por el
usuario es igual al que esta en la lista
cabeza = aux.getNext();
}
while (aux != null && aux.getNext() != null &&
aux.getInfo().getId() != id) { //Si id ingresado por el usuario no
es igual al que esta en la lista
if (aux.getNext().getInfo().getId() == id) { //Mientras que
sea igual, asigne la variable elimina
Celda elimina; //variable tipo celda
elimina = aux; //igualar la variable tipo celda con el
auxiliar
aux = aux.getNext();
elimina.setNext(aux.getNext()); //Asignar el valor de
elimina igual al siguiente para q no se imprima.
} else {
aux = aux.getNext(); //Si no se cumple, sigue buscando...
}
}
}
public void elimina(String NICK) {
Celda aux = cabeza; //se fija el auxiliar como la cabeza
if (aux.getInfo().getNICK().equals(NICK)) { //Si id ingresado por
el usuario es igual al que esta en la lista
cabeza = aux.getNext();
}
while (aux != null && aux.getNext() != null &&
!aux.getInfo().getNICK().equals(NICK)) { //Si id ingresado por el
usuario no es igual al que esta en la lista
if (aux.getNext().getInfo().getNICK().equals(NICK)) {
//Mientras que sea igual, asigne la variable elimina
Celda elimina; //variable tipo celda
elimina = aux; //igualar la variable tipo celda con el
auxiliar
aux = aux.getNext();
elimina.setNext(aux.getNext()); //Asignar el valor de
elimina igual al siguiente para q no se imprima.
} else {
aux = aux.getNext(); //Si no se cumple, sigue buscando...
}
}
}
// public void modifica(int id, String nombre) {
// //Taller
// Celda aux = cabeza; //se fija el auxiliar como la cabeza
// while (aux != null && aux.getInfo().getId() < id) { //Si id
ingresado por el usuario es menor al que esta en la lista
// aux = aux.getNext(); //asignarle un valor a aux
// }
// if (aux != null && aux.getInfo().getId() == id) {//Si id
ingresado por el usuario es igual al que esta en la lista
// clientThreadServer cambio; //varible tipo persona
// cambio= aux.getInfo(); // se iguala la variable tipo persona
// cambio.setNombre(nombre); // se hace el cambio al nuevo nombre
// }
// }
public clientThreadServer extrae(int id) {
//Taller
Celda aux = cabeza; //se fija el auxiliar como la cabeza
if (aux.getInfo().getId() == id) { //Si id ingresado por el
usuario es igual al que esta en la lista se asigna al siguiente
cabeza = aux.getNext(); //metodo para asignar al siguiente
}
while (aux != null && aux.getNext() != null &&
aux.getInfo().getId() != id) { //Si id ingresado por el usuario no
es igual al que esta en la lista
if (aux.getNext().getInfo().getId() == id) { //Si el valor id
es igual a algun valor en la lista
Celda elimina; //variable tipo celda
elimina = aux; // varible tipo celda es igual al auxiliar
aux = aux.getNext(); // obtener el siguiente elemento de
la lista
elimina.setNext(aux.getNext()); //
} else {
aux = aux.getNext(); //De lo contrario siga buscando
}
} //Si hay elementos que coinciden, entonces se extraen y luego
con el return siguiente se devuelve a la lista
return aux.getInfo();
}
@Override
public String toString() {
String s = "Room Mates ";
Celda aux = cabeza;
while (aux != null) {
s += aux.getInfo() + ", ";
aux = aux.getNext();
}
return s;
}
public void sendMessages(String msg) {
Celda aux = cabeza;
while (aux != null) {
aux.getInfo().sendBackClient(msg);
aux = aux.getNext();
}
}
}
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package vmatesserver;
public class Room implements Runnable {
private int ROOM_ID = 0;//ID para ingresar al ROOM
private Lista L = new Lista();
public Room(clientThreadServer client) {
if (ROOM_ID == 0) {
ROOM_ID = generaRoomID();
}
L.inserta(client);
System.out.println(L);
}
@Override
public void run() {
while (true) {
}
}
private int generaRoomID() {
return Static.ROOM_ID = Static.ROOM_ID + (int) (Math.random() * 500);
}
@Override
public String toString() {
return "ROOM_ID=" + ROOM_ID;
}
public int getROOM_ID() {
return ROOM_ID;
}
public Lista getL() {
return L;
}
}//CLASS END
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package vmatesserver;
import java.io.IOException;
import java.net.ServerSocket;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
public class Server {
// static final String REGISTER_REQUEST = "REGISTER_REQUEST";
// static final String NEW_ROOM = "NEW_ROOM";
// static final String JOIN_ROOM = "JOIN_ROOM";
// static final String REMOVE_MATE = "REMOVE_MATE";
// static final String FILE_TRANSFER = "FILE_TRANSFER";
// static final String MSG = "MSG";
// static int ROOM_ID = 22222;
// static int CLIENT_ID=1;
// static List<Room> Rooms;
// static clientThreadServer cliente;
private ServerSocket server;
public Server() {
try {
server = new ServerSocket(28001);
} catch (IOException ex) {
}
}
public void accept() {
while (true) {
try {
Static.cliente = new clientThreadServer(server.accept());
Static.cliente.start();
} catch (IOException ex) {
}
}
}
}
package vmatesserver;
import java.util.ArrayList;
import java.util.List;
/**
*
* @author murillke
*/
public class Static {
static final String REGISTER_REQUEST = "REGISTER_REQUEST";
static final String NEW_ROOM = "NEW_ROOM";
static final String JOIN_ROOM = "JOIN_ROOM";
static final String REMOVE_MATE = "REMOVE_MATE";
static final String FILE_TRANSFER = "FILE_TRANSFER";
static final String MSG = "MSG";
static final String SEND_MSG = "SEND_MSG";
static int ROOM_ID = 22222;
static int CLIENT_ID=1;
static List<Room> Rooms = new ArrayList<Room>();
static List<Byte> User;
static clientThreadServer cliente;
static Lista lista;
}
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package vmatesserver;
/**
*
* @author murillke
*/
public class VMatesServer {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
Server S = new Server();
S.accept();
}
}
package vmatesserver;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
public class clientThreadServer extends Thread {
private Socket socket;
private ObjectInputStream in;
private ObjectOutputStream out;
private String NICK;
private String email;
private int ID;
public clientThreadServer(final Socket socket) {
this.socket = socket;
startStreams();
}
public void sendBackClient(String msg) {
try {
System.out.println("Enviando mensaje a " + NICK + ": " + msg);
out.writeUTF(msg);
} catch (IOException ex) {
Logger.getLogger(clientThreadServer.class.getName()).log(Level.SEVERE,
null, ex);
}
}
private void startStreams() {
try {
in = new ObjectInputStream(socket.getInputStream());
out = new ObjectOutputStream(socket.getOutputStream());
} catch (IOException ex) {
}
}
@Override
public String toString() {
return "NICK= " + NICK + ", email= " + email + ", ID= " + ID;
}
// Formato de mensaje:"REGISTER_TYPE"+" "+"Name"+" "+"email"+"
"+"USER_ID"+" "+"ROOM_ID"+"MSG";
@Override
public void run() {
while (true) {
try {
String data = in.readUTF();
String[] msg_parts = data.split(" ", 6);
String msg_type = msg_parts[0];
switch (msg_type) {
case Static.MSG:
break;
case Static.REGISTER_REQUEST:
generaClientID();
NICK = msg_parts[1];
email = msg_parts[2];
out.writeUTF("MSG Server_found");
out.flush();
System.out.println(msg_parts[1] + " has registered");
break;
case Static.NEW_ROOM:
System.out.println("New Room has been requested");
generaClientID();
NICK = msg_parts[1];
email = msg_parts[2];
Room room = new Room(this);
(new Thread(room)).start();
Static.Rooms.add(room);
out.writeUTF("ROOM_&_ID" + " " + Static.ROOM_ID +
" " + Static.CLIENT_ID);
out.flush();
for (int i = 0; i < Static.Rooms.size(); i++) {
System.out.println(Static.Rooms.get(i).getROOM_ID());
}
// out.writeUTF("ROOM_&_ID" + " " + Static.ROOM_ID
+ " " + Static.CLIENT_ID);
// out.flush();
break;
case Static.SEND_MSG:
for (int i = 0; i < Static.Rooms.size(); i++) {
System.out.println("From List " +
Static.Rooms.get(i).getROOM_ID());
System.out.println("From Client " +
Integer.parseInt(msg_parts[4]));
if (Static.Rooms.get(i).getROOM_ID() ==
Integer.parseInt(msg_parts[4])) {
System.err.println("Sala encontrada");
Static.Rooms.get(i).getL().sendMessages(msg_parts[5]);
}
}
break;
case Static.JOIN_ROOM:
for (int i = 0; i < Static.Rooms.size(); i++) {
if (Static.Rooms.get(i).getROOM_ID() ==
Integer.parseInt(msg_parts[4])) {
generaClientID();
NICK = msg_parts[1];
email = msg_parts[2];
Static.Rooms.get(i).getL().inserta(this);
out.writeUTF("ROOM_&_ID" + " " + "null" +
" " + Static.CLIENT_ID);
out.flush();
System.out.println(Static.Rooms.get(i).getL());
}
}
break;
case Static.REMOVE_MATE:
for (int i = 0; i < Static.Rooms.size(); i++) {
if (Static.Rooms.get(i).getROOM_ID() ==
Integer.parseInt(msg_parts[4])) {
Static.Rooms.get(i).getL().elimina(Integer.parseInt(msg_parts[1]));
System.out.println(Static.Rooms.get(i).getL());
}
}
break;
case Static.FILE_TRANSFER:
for (int i = 0; i < Static.Rooms.size(); i++) {
}
break;
// if (data.length() > 0) {
//// for (int i = 0; i < Server.Users.size(); i++) {
//// Server.Users.get(i).out.writeUTF(data);
//// Server.Users.get(i).out.flush();
//// }
// System.out.println(data);
}
sleep(800);
} catch (IOException ex) {
} catch (InterruptedException ex) {
}
}
}
private void generaClientID() {
Static.CLIENT_ID = Static.CLIENT_ID + 1;
ID = Static.CLIENT_ID;
}
public String getNICK() {
return NICK;
}
public void setNICK(String NICK) {
this.NICK = NICK;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public int getID() {
return ID;
}
public void setID(int ID) {
this.ID = ID;
}
}
No comments:
Post a Comment