Java-套接字直到客户端断开连接才读取吗? [英] Java - Socket not reading until client disconnects?

查看:48
本文介绍了Java-套接字直到客户端断开连接才读取吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我用Java制作了带有套接字的服务器和客户端.我正在尝试让服务器从套接字读取/写入,但仅在客户端断开连接后才读取:

So I made a Server and Client with sockets in Java. I'm trying to get the server to read/write from the socket, but it only reads once the client disconnects:

        System.out.println("Server initialized");
        clientSocket = server.accept();
        System.out.println("Client connected");

        PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
        BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));

        for(int loop = 0;loop<5;loop++){
            out.write("Hello");
            System.out.println(in.readLine());
        }   //end for

问题在于,一旦客户端连接,它就会显示客户端已连接",但是它不会通过for循环运行.但是,一旦客户端断开连接,服务器将执行for循环并返回

The problem is that once the client connects, it says "Client connected" but then it doesn't run through the for loop. Once the client disconnects, however, the server executes the for loop and returns

null
null
null
null
null

我在这里想念什么?这是我的完整服务器代码:

What am I missing here? Here is my full server code:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

public class Server {
    public ServerSocket server;

    public Server(int port){
        try {
            server = new ServerSocket(port);
        } catch (IOException e) {
            System.out.println("Cannot bind to port: "+ port);
            System.exit(-1);
        }

    }   //end constructor

    public void WaitForClient() throws IOException{
        Socket clientSocket = null;

        try {
            System.out.println("Server initialized");
            clientSocket = server.accept();
            System.out.println("Client connected");

            PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
            BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));

            for(int loop = 0;loop<5;loop++){
                out.write("Hello");
                System.out.println(in.readLine());
            }   //end for

        }   //end try
        catch (IOException e) {
            System.out.println("Accept failed");
            System.exit(-1);
        }   //end catch

        clientSocket.close();
        server.close();

    }   //end method

}   //end class

(我的主要方法是从另一个类中调用的.)

(My main method is called from another class.)

推荐答案

如果要立即查看结果,则必须刷新服务器上的流.该流会在 close()上自动刷新,这就是为什么您随后看到输出的原因.

You have to flush the stream on the server if you want to see the results immediately. The stream is auto-flushed on close(), that's why you seen the output then.

这篇关于Java-套接字直到客户端断开连接才读取吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆