错误图片:图片
我正在创建一个与 2 个客户端的多线程客户端服务器聊天。程序没有错误,但我发送的消息没有到达客户端,我该怎么办?写你好#客户端1消息应该到达第二个客户端,但它没有。如何更改客户名称?下面我分别留下我写的服务器和客户端的文件:
import java.io.*;
import java.util.*;
import java.net.*;
public class Server{
static Vector<ClientHandler> lc = new Vector<>();
static int i = 0;
public static void main(String[] args) throws UnknownHostException, IOException{
ServerSocket ss = new ServerSocket(2104);
while (true){
Socket s = ss.accept();
System.out.println("Ricevuta nuova richiesta del client " + s);
DataInputStream dis = new DataInputStream(s.getInputStream());
DataOutputStream dos = new DataOutputStream(s.getOutputStream());
ClientHandler ch = new ClientHandler(s,"Client numero" + i, dis, dos);
Thread t = new Thread(ch);
System.out.println("Il client si sta aggiungendo alla lista");
lc.add(ch);
t.start();
i++;
}
}
}
class ClientHandler implements Runnable{
Scanner scn = new Scanner(System.in);
private String name;
final DataInputStream dis;
final DataOutputStream dos;
Socket s;
boolean login;
public ClientHandler(Socket s, String name, DataInputStream dis, DataOutputStream dos){
this.dis = dis;
this.dos = dos;
this.name = name;
this.s = s;
this.login=true;
}
@Override
public void run(){
String ricevuta;
while (true){
try{
ricevuta = dis.readUTF();
System.out.println(ricevuta);
if(ricevuta.equals("logout")){
this.login=false;
this.s.close();
break;
}
StringTokenizer st = new StringTokenizer(ricevuta, "#");
String MsgToSend = st.nextToken();
String recipient = st.nextToken();
for (ClientHandler mc : Server.lc){
if (mc.name.equals(recipient) && mc.login==true){
mc.dos.writeUTF(this.name+ " : " +MsgToSend);
break;
}
}
} catch (IOException e){
e.printStackTrace();
}
}
try{
this.dis.close();
this.dos.close();
}catch(IOException e){
e.printStackTrace();
}
}
}
import java.io.*;
import java.net.*;
import java.util.Scanner;
public class Client {
final static int ServerPort = 2104;
public static void main(String args[]) throws UnknownHostException, IOException{
Scanner scn = new Scanner(System.in);
InetAddress ip = InetAddress.getByName("localhost");
Socket s = new Socket(ip, ServerPort);
DataInputStream dis = new DataInputStream(s.getInputStream());
DataOutputStream dos = new DataOutputStream(s.getOutputStream());
Thread sendMessage = new Thread(new Runnable(){
@Override
public void run(){
while (true){
String messaggio = scn.nextLine();
try {
dos.writeUTF(messaggio);
} catch (IOException e){
e.printStackTrace();
}
}
}
});
Thread readMessage = new Thread(new Runnable(){
@Override
public void run(){
while (true){
try {
String messaggio = dis.readUTF();
System.out.println(messaggio);
} catch (IOException e){
e.printStackTrace();
}
}
}
});
sendMessage.start();
readMessage.start();
}
}