Websocket server.run()不允许启动后续代码

时间:2015-05-17 23:04:44

标签: java websocket java-websocket

我有http://java-websocket.org/的以下网络套接字服务器代码:

public class WebsocketServer extends WebSocketServer {

    private static int PORT = 2005;

    private Set<WebSocket> conns;

    public WebsocketServer() {
        super(new InetSocketAddress(PORT));
        conns = new HashSet<>();
    }

    @Override
    public void onOpen(WebSocket conn, ClientHandshake handshake) {
        conns.add(conn);
        System.out.println("New connection from " + conn.getRemoteSocketAddress().getAddress().getHostAddress());
    }

    @Override
    public void onClose(WebSocket conn, int code, String reason, boolean remote) {
        conns.remove(conn);
        System.out.println("Closed connection to " + conn.getRemoteSocketAddress().getAddress().getHostAddress());
    }

    @Override
    public void onMessage(WebSocket conn, String message) {
        System.out.println("Received: " + message);

        for (WebSocket sock : conns) {
            sock.send(messageToSend);
        }
    }

    @Override
    public void onError(WebSocket conn, Exception ex) {
        ex.printStackTrace();
        if (conn != null) {
            conns.remove(conn);
            // do some thing if required
        }
        System.out.println("ERROR from " + conn.getRemoteSocketAddress().getAddress().getHostAddress());
    }

    public static void main(String[] args) throws IOException, InterruptedException {
        WebsocketServer server = new WebsocketServer();
        server.run();

        BufferedReader sysin = new BufferedReader(new InputStreamReader(System.in));
        while (true) {
            String in = sysin.readLine();
            server.sendToAll(in);
            if (in.equals("exit")) {
                server.stop();
                break;
            } else if (in.equals("restart")) {
                server.stop();
                server.start();
                break;
            }
        }

    }

    public void sendToAll(String text) {
        Collection<WebSocket> con = connections();
        synchronized (con) {
            for (WebSocket c : con) {
                c.send(text);
            }
        }
    }
}

代码运行正常,但server.run();之后的所有代码都无法启动/工作!我需要将消息从Java控制台发送到客户端。

我做错了什么?

注意:我的客户端使用JavaScript工作,可以连接到服务器

1 个答案:

答案 0 :(得分:1)

您需要start() Runnable课程, run()直接

server.start();

而不是

server.run();