【问题标题】:Java Socket: Server won't read input until client server is closed -> Server can't response to clientJava Socket:在客户端服务器关闭之前,服务器不会读取输入 -> 服务器无法响应客户端
【发布时间】:2017-03-25 21:42:47
【问题描述】:

我正在尝试用 Java 建立一个基本的客户端 服务器连接。当尝试写入服务器时,客户端会正确发送详细信息,并且服务器会停止读取它,直到客户端输出流关闭。但是,一旦关闭输出流,它显然会关闭套接字,因此服务器无法回复客户端。这是处理此交互的主要代码 sn-p。

客户:

private void sendCmd(String cmd) {
    String infoToSend = cmd;
    try {
        socket = new Socket(hostname, port);
        System.out.println("Trying to send: " + com.sun.org.apache.xml.internal.security.utils.Base64.encode(infoToSend.getBytes()));
        out = new DataOutputStream(socket.getOutputStream());
        out.writeBytes(com.sun.org.apache.xml.internal.security.utils.Base64.encode(infoToSend.getBytes()));
        out.flush();
        System.out.println("Socket is flushed");


        System.out.println("Waiting for Data");
        InputStream is = socket.getInputStream();
        System.out.println("Trying to get data");
        BufferedReader input = new BufferedReader(
                new InputStreamReader(is)
        );

        String line;
        while((line = input.readLine()) != null) {
            System.out.println(line);
        }
        socket.close();
    } catch (IOException e) { e.printStackTrace(); }
}

服务器:

public void run() {
    System.out.println("Got Connection");
    try {
        BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        out = new DataOutputStream(socket.getOutputStream());

        String response;
        System.out.println("Response:");
        String decode = "";
        while ((response = in.readLine()) != null) {
            try {
                decode = new String(Base64.decode(response));
            } catch (Base64DecodingException e) {
                e.printStackTrace();
            }
        }


        System.out.println("Decoded: " + decode);
        out.writeBytes("We got your message!");
        out.flush();
        out.close();
    } catch (IOException e) { System.out.println("Fail"); e.printStackTrace(); }

谁能指导我如何解决这个错误。抱歉,如果它超级简单,我只是看不到它。

【问题讨论】:

  • 你在哪里打印 decode 变量?
  • @Omore 在我尝试调试时只是为了安慰

标签: java sockets


【解决方案1】:

发送

socket.shutdownOutput(); 

解决了这个问题。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-06-24
    • 2019-12-18
    • 2011-02-10
    • 1970-01-01
    • 1970-01-01
    • 2017-06-19
    • 1970-01-01
    相关资源
    最近更新 更多