Java客户端/服务器聊天

时间:2017-09-03 14:06:22

标签: java multithreading sockets

我的简单TCP / IP聊天出了问题。我的服务器似乎没有收到来自连接客户端的消息,我不知道它为什么会发生。 服务器代码:

public class ChatServer {

public static final int MAX_CLIENTS = 10;
public static final ClientHandler[] clients = new ClientHandler[MAX_CLIENTS];

public void go(int port){
    try (ServerSocket serverSocket = new ServerSocket(port)) {
        System.out.println("Connection established on port "+port);
        System.out.println("Waiting for clients...");

        while (true){
            Socket clientSocket = serverSocket.accept();
            for (int i=0; i<clients.length;i++){
                if (clients[i]==null){
                    ClientHandler clientHandler = new ClientHandler(clientSocket, clients);
                    clients[i] = clientHandler;
                    System.out.println("Added new client!");
                    clientHandler.start();
                    break;
                }
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
  }
}

ClientHandler类:

public class ClientHandler extends Thread {

private Socket socket;
private ClientHandler[] clients;
private PrintWriter out;

public ClientHandler(Socket clientSocket, ClientHandler[] clientsThreads){
    socket = clientSocket;
    clients = clientsThreads;
}

@Override
public void run() {
    ClientHandler[] threads = this.clients;
    try {
        BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        out = new PrintWriter(socket.getOutputStream(), true);

        for (int i=0; i<threads.length;i++){
            if (threads[i]!=null){
                threads[i].out.println("***SERVER: New client entered the chat room!***");
            }
        }

        while (true){
            System.out.println("in while loop - reading and writing to the client socket");
            String inputLine = in.readLine();
            System.out.println(inputLine);
            if (inputLine.startsWith("/quit")){
                break;
            }
            for (int i=0; i<threads.length;i++){
                if (threads[i]!=null){
                    threads[i].out.println(inputLine);
                }
            }
        }
        System.out.println("One of the clients is leaving the chat room");

        for (int i=0; i<threads.length;i++){
            if (threads[i]==this){
                threads[i]=null;
            }
        }
        out.close();
        in.close();
        socket.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
 }
}

客户端代码:

public class ChatClient {

private Socket socket;
private BufferedReader in;
private PrintWriter out;
private BufferedReader stdLine;
private boolean closed = false;


public void go(String hostName, int port){
    try {
        initializeResource(hostName, port);
        new Thread(new ServerReader()).start();
        while (!closed){
            out.println(stdLine.readLine().trim());
        }
        in.close();
        out.close();
        socket.close();
        System.out.println("Goodbye!");
    } catch (IOException e) {
        e.printStackTrace();
        System.out.println("Failed to connect, please try again.");
    }
}

public void initializeResource(String hostName, int port) throws IOException {
    socket = new Socket(hostName, port);
    in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
    out = new PrintWriter(socket.getOutputStream());
    stdLine = new BufferedReader(new InputStreamReader(System.in));
    System.out.println("Connection established!");
}

public class ServerReader implements Runnable{
    @Override
    public void run() {
        String inputLine = null;
        try {
            while ((inputLine=in.readLine())!=null){
                System.out.println(inputLine);
                if (inputLine.startsWith("Bye!")){
                    closed = true;
                    return;
                }
            }
            in.close();
            out.close();
            socket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

}

为服务器运行这些应用程序的结果:

 Connection established on port 8000
 Waiting for clients...
 Added new client!
 in while loop - reading and writing to the client socket

对于客户:

 Connection established!
 ***SERVER: New client entered the chat room!***

在客户端版本中,我可以一直在终端中写入消息,但服务器不会收到这些消息(否则消息将写入服务器的终端)。我将不胜感激任何建议。

1 个答案:

答案 0 :(得分:1)

您需要在从客户端打印一行后进行刷新:

    while (!closed){
        out.println(stdLine.readLine().trim());
        out.flush();
    }