java – How to write a server on sockets?

Question:

public static void main(String[] args) throws IOException {
    playerses = new ArrayList<>();
    serverSocket = new ServerSocket(7475);
    while (true) {
        Socket socket = serverSocket.accept();
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    while (true) {
                        String asd = new BufferedReader(new InputStreamReader(socket.getInputStream())).readLine();
                        System.out.println(asd);
                    }
                }
                catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }
}

You need to make sure that the server, after a client connects to it via a socket, starts listening to it.

while(true) is not bad code? Will it affect performance? Memory consumes, does the laptop eat? Or is there another way?

Answer:

I don't see anything particularly wrong with your code.

Writing your own bike server is a step worth going through.

Of the minuses – the allocation of a stream for each client. This will potentially make it impossible to handle, say, 10,000 clients at the same time. In sister .NET, the problem is solved using the async / await pattern, in Java, apparently, you will have to maintain the state of work with each of the clients manually.

Then, if your server actually uses a higher level protocol (HTTP?), it makes sense to use a ready-made client, the correct parsing of high-level complex protocols is another task. Although yes, this client will do essentially the same thing.

Scroll to Top