【问题标题】:While loop fails when socket reading input in java当套接字在java中读取输入时循环失败
【发布时间】:2014-03-05 02:51:27
【问题描述】:

所以我在读取来自客户的输入时遇到问题。每当我在服务器类中使用我的 if 语句而不用 while 语句包裹它时,它都可以正常工作。谁能指出我为什么会失败?

服务器类:

import java.io.*;
import java.net.*;

public class Server {

    public static void main(String[] args) throws Exception
    {
        Server myServer = new Server();
        myServer.run();
    }

    public void run() throws Exception
    {

        //Initializes the port the serverSocket will be on
        ServerSocket serverSocket = new ServerSocket(9999);
        System.out.println("The Server is waiting for a client on port 9999");
        //Accepts the connection for the client socket
        Socket socket = serverSocket.accept();

        InputStreamReader ir = new InputStreamReader(socket.getInputStream());
        BufferedReader br = new BufferedReader(ir);
        String message = br.readLine();
        //Confirms that the message was received
        System.out.println(message);

    //When this while is here.  The match fails and it goes to the else statement.
    //Without the while statement it will work and print "Received our hello message." 
    //when the client says HELLO.

     while(message != null)
     {
            if(message.equals("HELLO"))
            {
                PrintStream ps = new PrintStream(socket.getOutputStream());
                ps.println("Received our hello message.");
            }
            else
            {
                PrintStream ps = new PrintStream(socket.getOutputStream());
                ps.println("Did not receive your hello message");
            }
        }
    }
}

客户端类:

import java.io.*;
import java.net.*;
import java.util.*;

public class Client {

    public static void main(String[] args) throws Exception
    {
        Client myClient = new Client();
        myClient.run();
    }

    public void run() throws Exception
    {
        Socket clientSocket = new Socket("localhost", 9999);
        //Sends message to the server
        PrintStream ps = new PrintStream(clientSocket.getOutputStream());
        Scanner scan = new Scanner(System.in);
        String cMessage = scan.nextLine();
        ps.println(cMessage);
        //Reads and displays response from server
        InputStreamReader ir = new InputStreamReader(clientSocket.getInputStream());
        BufferedReader br = new BufferedReader(ir);
        String message = br.readLine();
        System.out.println(message);        
    }

}

【问题讨论】:

  • 什么不工作?我编译了你的代码,我得到了“收到我们的问候消息”。在客户端中输入 HELLO 后。
  • 当我取出while循环时它可以工作。除非我让它在接收到 HELLO 并在服务器窗口中打印之后什么都没有发生。
  • 一个好的做法是在程序结束时关闭所有套接字和阅读器。

标签: java sockets while-loop client-server client


【解决方案1】:

你永远不会在 while 循环中修改消息,所以你有一个无限循环。

试试

while((message = br.readLine()) != null)

【讨论】:

  • 我试过了,所以当客户端说 HELLO.. 服务器收到它并在服务器窗口中打印 HELLO,然后什么也没有发生。如果我尝试从客户端输入任何其他内容到服务器,它不会打印它已收到。
  • @Shawn,什么都不会发生,你只循环你的 br.readline,而你忘记循环你的 ps.printline
【解决方案2】:

您只在服务器端循环,而您忘记在客户端循环,我为您做了快速修复,还帮助您关闭了连接。

服务器.java

import java.io.*;
import java.net.*;

public class Server {

    public static void main(String[] args) throws Exception
    {
        Server myServer = new Server();
        myServer.run();
    }

    public void run() throws Exception
    {

        //Initializes the port the serverSocket will be on
        ServerSocket serverSocket = new ServerSocket(9999);
        System.out.println("The Server is waiting for a client on port 9999");
        //Accepts the connection for the client socket
        Socket socket = serverSocket.accept();

        InputStreamReader ir = new InputStreamReader(socket.getInputStream());
        BufferedReader br = new BufferedReader(ir);
        String message;
        //= br.readLine();
        //Confirms that the message was received

    //When this while is here.  The match fails and it goes to the else statement.
    //Without the while statement it will work and print "Received our hello message." 
    //when the client says HELLO.
        PrintStream ps = new PrintStream(socket.getOutputStream());
        while((message =br.readLine())!=null)
         {
             System.out.println(message);
                if(message.equals("HELLO"))
                {

                    ps.println("Received our hello message.");
                }
                if(message.equals("END"))
                {
                    ps.println("Client ended the connection");
                    break;
                }
                else
                {

                    ps.println("Did not receive your hello message");
                }
        }
        ps.close();
        br.close();
        ir.close();
        serverSocket.close();
    }
}

客户端.java

import java.io.*;
import java.net.*;
import java.util.*;

public class Client {

    public static void main(String[] args) throws Exception
    {
        Client myClient = new Client();
        myClient.run();

    }

    public void run() throws Exception
    {
        Socket clientSocket = new Socket("localhost", 9999);
        //Sends message to the server
        PrintStream ps = new PrintStream(clientSocket.getOutputStream());
        Scanner scan = new Scanner(System.in);
        String cMessage ="";
        InputStreamReader ir = new InputStreamReader(clientSocket.getInputStream());
        BufferedReader br = new BufferedReader(ir);
        while(!(cMessage.trim().equals("END"))){
        cMessage = scan.nextLine();
        ps.println(cMessage);
        //Reads and displays response from server
        String message = br.readLine().trim();
        System.out.println(message);
        }
        br.close();
        ir.close();
        scan.close();
        ps.close();
        clientSocket.close();
    }

}

【讨论】:

  • Awesome 工作得非常好......只需要添加 else if 对于消息 == 到 BYE。感谢您的帮助先生并标记为已回答。
【解决方案3】:

您的代码可以正常发送一条“HELLO”消息。 但是,就像 ^Tyler 指出的那样,如果您想继续发送消息,您需要在 while 循环中移动 'while((message = br.readLine()) != null)'。

【讨论】:

  • 好的,所以如果我将它移动到 while 语句(这两行):String message = br.readLine(); System.out.println(消息);它将打印出 Received our hello message。但随后它在 Server.run(第 30 行)和 Server.main(第 9 行)的线程“main”java.lang.NullPointerException 中出现异常
  • Shawn,您一定忘记在 while 循环之外删除 br.readLine(),因为您在 while 循环中使用它。这就是为什么它只是打印,甚至不进入 while 循环!
  • 我刚才提到你应该阅读while循环中的消息。我将编辑我的帖子以使其清楚!
  • 还记得在客户端循环输入。
【解决方案4】:

像你一样使用循环......

String line;
while ((line = in.readLine()) != null) {
    System.out.println(line);
    sleep(in);
    if(!in.ready()){
        break;
    }
}

我想出了一个作弊的方法。

private static void sleep(BufferedReader in) throws IOException {
    long time = System.currentTimeMillis();
    while(System.currentTimeMillis()-time < 1000){
        if(in.ready()){
            break;
        }
    }       
}

这可能有点草率,但是如果您创建一个等待一段时间的睡眠方法,然后继续检查 BufferedReader 是否“准备就绪”。如果是的话,你可以突破,但是当你出来的时候再检查一次。 -- 也许你可以只返回一个布尔值而不是检查两次,但这个概念就在那里。

【讨论】:

    猜你喜欢
    • 2014-08-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-11
    • 2012-03-17
    • 2017-10-29
    • 1970-01-01
    相关资源
    最近更新 更多