简单的Java echo服务器问题

我正在尝试编写我的第一个套接字服务器,所以我决定从一个非常简单的事情开始,只是为了计算流程:)我正在编写一个简单的
java echo服务器,但问题是(出于某种原因?! )我没有在客户端获得服务器响应,但是在服务器中收到了请求.

package poc.client;

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

public class Client {
    public static void main(String[] args) {
        try {
            final Socket socket = new Socket((String) null, 50000);

            final BufferedReader reader = new BufferedReader(
                    new InputStreamReader(socket.getInputStream()));
            final PrintWriter writer = new PrintWriter(
                    socket.getOutputStream(), true);
            writer.println("ala bala\r\n");
            writer.flush();
            writer.close();

            System.out.println(reader.readLine());
            System.out.flush();
        } catch (Exception ex) {
                Logger.getAnonymouseLogger().throwing(TAG, "main", ex);
        }

    }
}

而服务器部分是

package poc.server;

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 {

    /**
     * debugging purposes only
     */
    @SuppressWarnings("unused")
    private static final String TAG = Server.class.getSimpleName();

    public static void main(String[] args) {
        try {
            final ServerSocket socket = new ServerSocket(50000);
            while (true) {
                final Socket clientSocket = socket.accept();
                final BufferedReader reader = new BufferedReader(
                        new InputStreamReader(clientSocket.getInputStream()));
                final PrintWriter writer = new PrintWriter(clientSocket
                        .getOutputStream(), true);

                writer.println(reader.readLine());
                writer.flush();
                writer.close();
            }
        } catch (IOException e) {
                Logger.getAnonymouseLogger().throwins(TAG, "main",ex);
        }

    }
}

我阅读了所有的Oracle基本套接字教程/等,但我无法弄清楚是什么问题 – 我已成功写入服务器套接字但我似乎无法得到响应.

最佳答案 在从套接字读取之前不要关闭写入器.以下代码有效

final Socket socket = new Socket((String) null, 50000);

            final BufferedReader reader = new BufferedReader(
                    new InputStreamReader(socket.getInputStream()));
            final PrintWriter writer = new PrintWriter(
                    socket.getOutputStream(), true);
            writer.println("ala bala\r\n");

            System.out.println(reader.readLine());            
            //writer.flush();
            writer.close();

根据close()方法的javadoc:

Closes the stream and releases any system resources associated with
it. Closing a previously closed stream has no effect.

看起来如果关闭流,底层套接字也会关闭.您可以通过在当前代码中打印堆栈跟踪来验证这一点.它给出了java.net.SocketException:socket关闭错误.

点赞