使用BufferedReader

时间:2017-02-21 21:11:51

标签: java sockets

我在使用围绕Java中的BufferedReader的while循环时遇到了问题。我正在用套接字做一些实验。

我目前的代码:

InetAddress address = InetAddress.getByName(this.IP);
        SocketAddress socketaddress = new InetSocketAddress(address, this.port);
        Socket socket = new Socket();
        socket.connect(socketaddress);

        if(socket.isConnected()){

            Executor.logger.info("Connection to proxy established!");

        }
        else {

            Executor.logger.warning("Connection to proxy failed!");
            socket.close();
            return;

        }

        BufferedWriter out = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
        BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));

        String temp2;
        while((temp2 = in.readLine()) != null){

            Executor.logger.info("Running query says " + temp2);

        }

但无论我尝试过什么,代码都不会进入下一行。它不会向我的记录器发送垃圾邮件,只是突然停止并卡住。

这只是客户端,我无法控制接收方服务器端。

我做错了吗?

感谢您提前提供任何帮助。

编辑

服务器是一个命令行,它接受带有变量的命令,并返回一个代码,告诉你刚刚做了什么的结果。但是,当你第一次连接时,它会返回一些消息,空白行,消息,空白行,这是当前卡住的循环。

1 个答案:

答案 0 :(得分:0)

经过测试,我找到了一个替代变量,可用于检测BufferedReader是否已满。

如果从此代码更改((temp2 = in.readLine())!= null):

BufferedWriter out = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
    BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));

    String temp2;
    while((temp2 = in.readLine()) != null){

        Executor.logger.info("Running query says " + temp2);

    }

并使用boolean(in.ready())代替:

BufferedWriter out = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
        BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));

        out.write("login " + this.user + " " + this.password);
        out.flush();

        String temp2;
        while(in.ready()){

            temp2 = in.readLine();

            Executor.logger.info("Running query says " + temp2);

        }

当BufferedRead没有更多数据要读取时,它将停止循环,并且可以在必要时通过再次复制循环再次重新初始化。