gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 07:55:56 25 4
gpt4 key购买 nike

这是我的代码,当我在 Eclipse 中以 Debug模式运行它时,它显示它不会继续,它会停留在我放置箭头的代码中。

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

最佳答案

您的套接字已在这一行创建。因为服务器绑定(bind)到一个端口,所以此时 ServerSocket 构造函数被调用。至于接受方法,due to 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. This could result in a SecurityException.

所以,accept方法只是在等待客户端连接,这就是执行在此时停止的原因。也许,阅读 java official tutorial 可能会有所帮助。用于编写服务器端。

关于java - TCP 连接,serversocket.accept 运行时不会创建套接字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32671524/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com