在简单的聊天应用程序上显示连接的用户

时间:2017-03-26 22:18:28

标签: java multithreading sockets io

我在这个多客户端聊天应用程序中遇到了问题。

在输入消息之前,程序不会显示已连接用户的列表。 此外," readLine"在&#34之前输入您的信息"。

下图显示了与客户的互动:

enter image description here

服务器类:

public class Server {
public static ArrayList<Client> list;
private static ServerSocket sock;
private static BufferedReader br;
private static Socket link;

public static void main(String[] args){
    list = new ArrayList<Client>();
    try{
        sock = new ServerSocket(1777);
    }catch(IOException ex){
        ex.printStackTrace();
    }
    Client c = null;
    do{
        try {
            link  = sock.accept();
            System.out.println("New user is connected : " + link);
            br = new BufferedReader(new InputStreamReader(link.getInputStream()));
            c = new Client(link, br.readLine());
            System.out.println("Welcome : " + c.getPseudo());
            list.add(c);
            new Service(c, br).start();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }while(true);
}

线程服务类:

public class Service extends Thread{
private Socket link;
private PrintWriter pw;
private BufferedReader br;
private ArrayList<Client> oldList;

public Service(Client c, BufferedReader br) throws IOException{
    link = c.getSocket();
    this.br=br;
    pw = new PrintWriter(link.getOutputStream(), true);
    oldList= new ArrayList<Client>(Server.list);
}

@Override
public void run(){
    String[] cmd = null;
    String to = "";
    String msg = "";
    PrintWriter msgSender=null;
    pw.println("Connected users : ");
    for(Client c : Server.list){
      pw.println(c.getPseudo());
    }
...
        }   
    }

用户类:

public class User {
public static void main(String[] args) {
    Socket link=null;
    BufferedReader input = null;
    PrintWriter output = null;
    Scanner s = new Scanner(System.in);
    System.out.print("Type your username : ");
    String pseudo = s.nextLine();
    String cmd; 
    try{
        link = new Socket(InetAddress.getLocalHost(), 1777);
        output = new PrintWriter(link.getOutputStream(), true);
        input = new BufferedReader(new InputStreamReader(link.getInputStream()));
        output.println(pseudo);
        while(true){
            while(input.ready()) System.out.println(input.readLine());
            System.out.print("Type your message : ");
            cmd = s.nextLine();
//                output.println(cmd);
            }
        }catch(IOException ex){
            ex.printStackTrace();
        }

    }
}

客户类:

public class Client {
private Socket link;
private String pseudo;

public Client(Socket link, String pseudo){
    this.link = link;
    this.pseudo=pseudo;
}

@Override
public boolean equals(Object o){
    Client c = (Client) o;
    return (this.pseudo.equals(c.pseudo));
}

public Socket getSocket() {
    return link;
}

public String getPseudo() {
    return pseudo;
}

}

0 个答案:

没有答案