简体   繁体   English

TCP连接,serversocket.accept在运行时不会创建套接字

[英]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. 这是我的代码,当我在eclipse中以调试模式运行它时,它向我显示它不会继续运行,从而停止了停留在我放置箭头的代码中。

    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. 由于服务器绑定到端口,因此将调用ServerSocket构造函数。 As for accept method, due to JavaDoc it 至于accept方法, 由于JavaDoc的缘故

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. 创建一个新的Socket,如果有安全管理器,则使用s.getInetAddress()。getHostAddress()和s.getPort()作为其参数来调用安全管理器的checkAccept方法,以确保允许该操作。 This could result in a SecurityException. 这可能会导致SecurityException。

So, accept method is just waiting for client connections, that is the reason, why execution stops at this point. 因此,accept方法只是在等待客户端连接,这就是为什么此时执行停止的原因。 May be, it could be helpfull to read a java official tutorial for writing a server side. 可能是,阅读Java官方教程来编写服务器端可能会有所帮助。

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. 当客户端要连接它时,它将与该套接字连接,程序流进入下一行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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