Skip to content
Advertisement

Why are multiple sockets created by one client

Multiple sockets created by one client

The task is to create a server-client communication with sockets. The client is the browser and it requests an html file. The server listens and accepts the connection if a request is made.

I would like to create one thread/client (persisten connection), but can’t figure out why are multiple sockets created for one request.

Server

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

public class Server {
    private ServerSocket serverSocket;

    public Server(int port) {
        try {
            serverSocket = new ServerSocket(port);
        } catch (IOException e) {
            e.printStackTrace();
        }

        int i = 0;
        while (true) {
            try {
                Socket socket = serverSocket.accept();
                Thread t = new HandleClient(i, socket);
                t.start();
                System.out.println("port:" + socket.getPort() + " is connected to " + socket.getInetAddress());
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        new Server(2001);
    }
}

Example

port:50065 is connected to /0:0:0:0:0:0:0:1
port:50066 is connected to /0:0:0:0:0:0:0:1
port:50064 is connected to /0:0:0:0:0:0:0:1

Advertisement

Answer

ServerSocket.accept() “…blocks until a connection is made.”

When I test your code, the program go no further than up to this accept() method and wait for connection.

Trying to connect in the same loop by your HandleClient thread stated after accept() is impossible.

I don’t know what can be the problem that you are receiving any output at all, maybe you have some other working threads, on different programs that are connecting with 2001 port?

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement