2
I have a question with java sockets. My code sends messages to all customers, including what you send. I want it to send only to other customers. Is there any way to do this? I test using the command telnet 127.0.0.1 2015
in the terminal.
Client
package socket;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
public class Clientes implements Runnable {
public Socket cliente;
public Clientes(Socket cliente) {
this.cliente = cliente;
}
public void run() {
try {
PrintWriter out = new PrintWriter(cliente.getOutputStream(), true);
out.write("---Seja Bem Vindo---\n");
out.flush();
System.out.println("Nova conexao: "
+ this.cliente.getInetAddress().getHostAddress());
while (true) {
BufferedReader in = new BufferedReader(new InputStreamReader(
cliente.getInputStream()));
String veioDoCliente = in.readLine();
if(veioDoCliente.equalsIgnoreCase("SAIR")){
cliente.close();
break;
}
System.out.println("MSG vinda do cliente " + veioDoCliente);
for (Clientes writer : Servidor.clientes) {
PrintWriter out2 = new PrintWriter(writer.cliente.getOutputStream(), true);
out2.write("teste:"+veioDoCliente+"\n");
out2.flush();
}
//s.close();
//this.cliente.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
Server
package socket;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
public class Servidor {
public Socket cliente;
public Servidor(Socket cliente) {
this.cliente = cliente;
}
public static List<Clientes> clientes = new ArrayList<Clientes>();
public static void main(String[] args) throws IOException {
ServerSocket servidor = new ServerSocket(2015);
System.out.println("Esperando alguem se conectar...");
while (true) {
Socket cliente = servidor.accept();
Clientes tratamento = new Clientes(cliente);
clientes.add(tratamento);
Thread t = new Thread(tratamento);
t.start();
}
}
}