java: closing client socket resets server socket

≡放荡痞女 提交于 2019-12-08 00:24:25

What happens is a normal behaviour. You server code only includes handling of a single client. The listener.accept() function only accepts latest connection to server. You need to put the listened.accept() in loop and handle all the exceptions that are raised within. The server-side code should look like this:

public class Server
{
    public static void main(String[] args) throws IOException
    {
        try(ServerSocket listener = new ServerSocket(9090);
        while (true) {
            try {
                        Socket socket = listener.accept();)
                        …
            } catch (SocketException ex) {
                ...
            }
        }
    }
}

But keep in mind that this code will only handle single client at a time. No multi-threading in this code.

Your Server is closing the connection and then finishing becuase it is created outside the while loop. I believe this is what you need.

public class Server {
    public static void main (final String[] args)
            throws IOException {

        while (true) {

            try (ServerSocket listener = new ServerSocket(9090); Socket socket = listener.accept();) {

                while (true) {
                    final BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                    final PrintWriter out = new PrintWriter(socket.getOutputStream(), true);

                    System.out.println("Started...");

                    final String transform = br.readLine();
                    if (transform == null) 
                        break;

                    final String newStr = transform.toUpperCase();

                    out.println(newStr);
                }
            }
        }
    }
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!