Alfredo Siprian
Alfredo Siprian

Reputation: 13

TCP connection, serversocket.accept when running it wont create the socket

This is my code when I run it in debug mode in eclipse it shows me that it doesn´t continue it stops a stays in the code where I have put an arrow.

    private ServerSocket serverSocket = null;
    private Socket socket= null;
    private ObjectInputStream inputStream= null;    
public void ConnectTCP(){
        try{
            serverSocket = new ServerSocket(5000);
       ---->socket = serverSocket.accept();
            inputStream = new ObjectInputStream(socket.getInputStream());
            System.out.print("Server is Running");
        }catch(IOException e){
            e.printStackTrace();
        }
    }

Upvotes: 1

Views: 54

Answers (2)

Stanislav
Stanislav

Reputation: 28126

Your socket is already created at this line. Because server binds to a port, at the moment ServerSocket constructor is called. As for accept method, due to JavaDoc it

Listens for a connection to be made to this socket and accepts it. The method blocks until a connection is made. A new Socket s is created and, if there is a security manager, the security manager's checkAccept method is called with s.getInetAddress().getHostAddress() and s.getPort() as its arguments to ensure the operation is allowed. This could result in a SecurityException.

So, accept method is just waiting for client connections, that is the reason, why execution stops at this point. May be, it could be helpfull to read a java official tutorial for writing a server side.

Upvotes: 1

ashiquzzaman33
ashiquzzaman33

Reputation: 5741

Actually it won't stop, it waiting for connection. When a client want to connect it then it connect with that socket and program flow goes next line.

Upvotes: 0

Related Questions