简体   繁体   中英

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();
        }
    }

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM