ServerSide:读取直到从客户端输入“结束”字符串

时间:2014-12-23 10:31:00

标签: java networking network-programming

我是Java编写的初学者,对不起,如果这个问题很愚蠢..我遇到的问题是当我从ClientSide编写文本时,它似乎没有正确地通过while循环服务器端。你能否就如何解决它提出一些指示。提前谢谢!

public void enterMessage() throws IOException {
    String topic;
    String currentLine = "", text = "";
    String receiver;
    BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
    int id = messages.lastIndexOf(messages);
    out.writeUTF("The users you can message are: " + Server.users.toString() + "\nEnter the user you want to message: ");
    receiver = in.readUTF();
    for (int i = 0; i < Server.users.size(); i++) {         
        if(receiver.equals(Server.users.get(i).username)) {
            out.writeUTF("You are writing to: " + Server.users.get(i).username + "\nEnter the topic: ");
            topic = in.readUTF();
            out.writeUTF("Enter your message(write 'end' on a new line to finish): ");
            do {
                currentLine = br.readLine();
                text.concat(currentLine);
            }
           while(!currentLine.equalsIgnoreCase("end"));
            //Server.sendToUser(receiver);
            Message msg = new Message(username,receiver,id,topic,text);
            messages.add(msg);
            out.writeUTF("Message saved.");
            break;
    }
        else
            out.writeUTF("This user does not exist.");
    }
}

1 个答案:

答案 0 :(得分:0)

currentLine = br.readLine();移出while循环,如:

currentLine = br.readLine();
while(!currentLine.equalsIgnoreCase("end")) {

原因是:

您将currentLine初始化为空字符串,并且只有在输入while循环时才会更改currentLine,这会检查条件,如是&#34;空字符串&#34;等于&#34;结束&#34;这将永远不会发生,你的代码不会在循环中进入。