如何从客户端读取多行到服务器

how to read multiple lines from client to server

因此,每次我在客户端控制台中键入内容时,我都会尝试发送多行代码。然而,当这样做时,它只在服务器中打印一次客户端的输出,我想做的是每次输入一行后在服务器中打印客户端输出。

客户:

    try {
        
        Scanner scanner = new Scanner(System.in);
        
        DataInputStream inputStream = new DataInputStream(socket.getInputStream());
        DataOutputStream outputStream;
        
        System.out.println("Write something to client:");
        
        while(scanner.hasNext()) {
            
            System.out.println("Write something to client:");
            outputStream = new DataOutputStream(socket.getOutputStream());
            
            
            String message = scanner.nextLine();
            
            outputStream.writeUTF(message);
        }
        
    } catch (IOException e) {
        System.out.println("[ERROR] Unable to get streams from server");
    }
}

客户端线程:

    @Override
public void run() {
    
    try {
        
        DataInputStream inputStream = new DataInputStream(socket.getInputStream());
        DataOutputStream outputStream = new DataOutputStream(socket.getOutputStream());
        
        System.out.println(inputStream.readUTF());
        
    } catch (IOException e) {
        e.printStackTrace();
    }
}

服务器: public服务器(){

    try {
        serverSocket = new ServerSocket(port);
        System.out.println("[SERVER] Server initialized successfully");
        // consider using!
        Runtime.getRuntime().addShutdownHook(new Thread());

    } catch (IOException e) {
        System.out.println("[ERROR] Unable to launch server on port " + port);
    }

    while (true) {
        Socket socket = null;

        try {
            socket = serverSocket.accept();
        } catch (IOException e) {
            System.out.println("[ERROR] Unable to accept client request");
        }

        System.out.println("[SERVER] New user joined the chat: " + socket);

        groupCounter++;
        ClientThread client = new ClientThread("Client " + groupCounter, socket);

        Thread thread = new Thread(client);
        thread.start();

        groupClients.add(client);

        //System.out.println(groupCounter);

        
        
    }

问题出在服务器端,serverSocket.accept()停止执行并等待客户端连接到服务器套接字。这就是为什么您每次只收到一条消息。

在 ClientThread 中添加一个无限循环以确保它继续读取客户端套接字输入。

try {
    while (true) {
        DataInputStream inputStream = new DataInputStream(socket.getInputStream());
        DataOutputStream outputStream = new DataOutputStream(socket.getOutputStream());

        System.out.println(inputStream.readUTF());
    }
} catch (IOException e) {
    e.printStackTrace();
}