1
I need to replicate a client’s message to everyone who’s connected except the client you sent. Below is the classes I have so far. How could I replicate these messages?
public class Servidor {
public static final int porta = 4444;
private ServerSocket serverSocket;
public static void main(String[] args) {
try {
new Servidor().iniciarServidor();
} catch (IOException e) {
e.printStackTrace();
}
}
public void iniciarServidor() throws IOException {
serverSocket = new ServerSocket(porta);
System.out.println("Servidor esperando conexões..");
while (true) {
Socket socket = serverSocket.accept();
ThreadServidor st = new ThreadServidor(socket);
st.start();
}
}
}
public class Cliente {
private static Socket socket;
private Scanner scanner;
public static void main(String[] args) throws UnknownHostException, IOException {
new Cliente().iniciarCliente();
}
public void iniciarCliente() throws UnknownHostException, IOException {
System.out.println("Digite seu nome: ");
scanner = new Scanner(System.in);
String nome = scanner.nextLine();
socket = new Socket("localhost", 4444);
PrintWriter pw = new PrintWriter(socket.getOutputStream(), true);
BufferedReader bf = new java.io.BufferedReader(new InputStreamReader(System.in));
while (true) {
String leitura = bf.readLine();
pw.println(nome + ": " + leitura);
}
}
}
public class ThreadServidor extends Thread {
private Socket socket;
PrintWriter printWriter = null;
public ThreadServidor(Socket socket) {
this.socket = socket;
}
public void run() {
try {
String mensagem = null;
BufferedReader bf = new BufferedReader(new InputStreamReader(socket.getInputStream()));
while ((mensagem = bf.readLine()) != null) {
System.out.println("Mensagem do cliente: " + mensagem);
}
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
What’s wrong with the code?
– ramaral
Nothing, just doesn’t send to all connected clients.
– Marcelo Henrique