我对java套接字有疑问。我的代码向所有客户端发送消息,包括发送。我希望他只为其他客户发送我怎么能这样做?我在终端中使用telnet 127.0.0.1 2015
命令进行测试。
客户端
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();
}
}
}
服务器
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();
}
}
}
答案 0 :(得分:0)
我没看到你的服务器处理代码的位置,所以我在黑暗中拍摄。
基本上,当您的数据进入时,您会看到它来自哪个客户端,然后检查您的循环以查看该客户端是否与当前客户端匹配。如果不匹配,则将数据发送出去。
如果其他方式无法实现,您将需要为每个客户端和ID提供,并且它将使用ID字符串发送数据,但我确信您可以使用套接字跟踪客户端。