简体   繁体   English

为什么ServerSocket.accept()不起作用?

[英]Why wont ServerSocket.accept() work?

Before I ask this question I would to apologise because of the fact that I have no idea what has gone wrong here, so I'm just saying in advanced that this may be a pain in the neck to follow. 在我提出这个问题之前,我会道歉,因为我不知道这里出了什么问题,所以我只是提前说这可能是一个痛苦的问题。

public void setUp(){
    try {
        port = Integer.parseInt(JOptionPane.showInputDialog("Enter the port to host server on"));
        server = new ServerSocket(port);
        System.out.println(server.getLocalPort());
        connection = server.accept();
        out = new PrintWriter(connection.getOutputStream());
        in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        connected = true;
        loop();
    } catch (Exception e) {
        connected = false;
        System.err.println(e.getMessage());
        JOptionPane.showMessageDialog(null, "Something went wrong there, be sure to use syntax:\nport: 1337\nMaybe the selected port is in use?");
        System.exit(-1);
    }
}

The code above should make it so that i can set up a basic server that any client can connect to, I don't think the client code is relevant at this time, but if it is needed then please ask. 上面的代码应该这样我可以设置任何客户端可以连接的基本服务器,我不认为客户端代码目前是相关的,但如果需要,那么请询问。

anyway, my question, when I call this method it runs fine until it hits 无论如何,我的问题,当我调用这种方法时,它运行良好,直到它击中

connection = server.accept();

and then the method just ends as if I typed return; 然后该方法就像我键入return一样结束; !

Can anyone tell me why this happens and how to fix it? 谁能告诉我为什么会发生这种情况以及如何解决这个问题?

Also note 另请注意

port = Integer for the port server = ServerSocket connection = Socket out = PrintWriter in = BufferedReader connected = boolean port =端口服务器的整数= ServerSocket connection = Socket out = PrintWriter in = BufferedReader connected = boolean

Maybe it only looks like it ends because connection = server.accept(); 也许它看起来只是因为connection = server.accept(); will make thread wait till client connects. 将使线程等待直到客户端连接。

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

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