WebSocketClient已断开RemoteEndpoint不可用

时间:2016-05-16 13:01:33

标签: java websocket jetty

我正在尝试在Thread中实现WebSocketClient,其中Client不断向服务器发送消息,但我看到了Exception:

  

org.eclipse.jetty.websocket.api.WebSocketException:RemoteEndpoint   不可用,当前状态[CLOSED],期待[OPEN或CONNECTED]

这是代码:

public class ProcessAnalysisThread extends Thread {

    static String dest = "ws://localhost:8086/Echo/";
    WebSocketClient client;
    EAMClientSocket socket;

    public void run() {
        initializeWSClient();

        while (true) {
            System.out.println("Thread running");
            try {
                Thread.sleep(500);
                socket.sendMessage("echo");
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

    }

    void initializeWSClient() {

        client = new WebSocketClient();
        try {

            socket = new EAMClientSocket(this);
            client.start();
            URI echoUri = new URI(dest);
            System.out.println("URI Resolved");
            ClientUpgradeRequest request = new ClientUpgradeRequest();
            client.connect(socket, echoUri, request);
            System.out.println("Connected and Waiting .....");
            socket.getLatch().await();
            System.out.println("Latched");

            System.out.println("RequestURI: " + request.getRequestURI().toString());

            socket.sendMessage("echo");
            System.out.println("Sent Msg: echo");
            socket.sendMessage("test");
            System.out.println("Sent Msg: test");
//          Thread.sleep(10000l);

        } catch (Throwable t) {
            System.out.println("Exception");
            t.printStackTrace();
        } finally {
            try {
                client.stop();
            } catch (Exception e) {
                System.out.println("Exception1");
                e.printStackTrace();
            }
        }
    }

}

这是输出:

Connected and Waiting .....
Connected to server
Latched
RequestURI: ws://localhost:8086/Echo/
Sent Msg: echo
Sent Msg: test
Message received from server:echo
Message received from server:test
Thread running
Exception in thread "Thread-0" org.eclipse.jetty.websocket.api.WebSocketException: RemoteEndpoint unavailable, current state [CLOSED], expecting [OPEN or CONNECTED]
    at org.eclipse.jetty.websocket.common.WebSocketSession.getRemote(WebSocketSession.java:252)

看起来我的线程没有在这里持有套接字引用

0 个答案:

没有答案