websocket客户端不返回连接

时间:2019-03-24 21:06:57

标签: java websocket

我有websocket服务器,现在我需要客户端来测试其用法。我正在使用此客户代码:

import org.msgpack.MessagePack;
import org.springframework.web.socket.BinaryMessage;

import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;

public class TestApp {

    public static void main(String[] args) {
        try {
            // open websocket
            final WebsocketClientEndpoint clientEndPoint = new WebsocketClientEndpoint(new URI("ws://localhost:8080/websocket"));

            // add listener
            clientEndPoint.addMessageHandler(new WebsocketClientEndpoint.MessageHandler() {
                public void handleMessage(String message) {
                    System.out.println(message);
                }
            });

            // send message to websocket

            clientEndPoint.sendMessage(new BinaryMessage(...));

            // wait 5 seconds for messages from websocket
            Thread.sleep(5000);

        } catch (InterruptedException ex) {
            System.err.println("InterruptedException exception: " + ex.getMessage());
        } catch (URISyntaxException ex) {
            System.err.println("URISyntaxException exception: " + ex.getMessage());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

import org.springframework.web.socket.BinaryMessage;

import java.net.URI;
import javax.websocket.ClientEndpoint;
import javax.websocket.CloseReason;
import javax.websocket.ContainerProvider;
import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.WebSocketContainer;


@ClientEndpoint
 class WebsocketClientEndpoint {

    Session userSession = null;
    private MessageHandler messageHandler;

    public WebsocketClientEndpoint(URI endpointURI) {
        try {
            WebSocketContainer container = ContainerProvider.getWebSocketContainer();
            container.connectToServer(this, endpointURI);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * Callback hook for Connection open events.
     *
     * @param userSession the userSession which is opened.
     */
    @OnOpen
    public void onOpen(Session userSession) {
        System.out.println("opening websocket");
        this.userSession = userSession;
    }

    /**
     * Callback hook for Connection close events.
     *
     * @param userSession the userSession which is getting closed.
     * @param reason the reason for connection close
     */
    @OnClose
    public void onClose(Session userSession, CloseReason reason) {
        System.out.println("closing websocket");
        this.userSession = null;
    }

    /**
     * Callback hook for Message Events. This method will be invoked when a client send a message.
     *
     * @param message The text message
     */
    @OnMessage
    public void onMessage(String message) {
        if (this.messageHandler != null) {
            this.messageHandler.handleMessage(message);
        }
    }

    /**
     * register message handler
     *
     * @param msgHandler
     */
    public void addMessageHandler(MessageHandler msgHandler) {
        this.messageHandler = msgHandler;
    }

    /**
     * Send a message.
     *
     * @param message
     */
    public void sendMessage(BinaryMessage message) {
        this.userSession.getAsyncRemote().sendObject(message);
    }

    /**
     * Message handler.
     *
     * @author Jiji_Sasidharan
     */
    public static interface MessageHandler {

        public void handleMessage(String message);
    }
}

运行此客户端时,我的服务器接受它,我正在使用spring和

void afterConnectionEstablished(WebSocketSession session)

BinaryWebSocketHandler的方法启动,一切似乎都很好,但是在此方法之后,客户端未设置userSession,它仍然为null,因此始终在其上抛出nullpointer异常

this.userSession.getAsyncRemote().sendObject(message);

这是奇怪的cuz服务器接受连接。是什么导致此问题?有解决办法吗?

感谢帮助!

1 个答案:

答案 0 :(得分:0)

package websocket.client;
import java.net.URI;
import javax.websocket.*;
@ClientEndpoint
public class WSClient {
private static Object waitLock = new Object();
@OnMessage
public void onMessage(String message) {
    //the new USD rate arrives from the websocket server side.
    System.out.println("Received msg: " + message);
}
private static void wait4TerminateSignal() {
    synchronized(waitLock) {
        try {
            waitLock.wait();
        } catch (InterruptedException e) {}
    }
}
public static void main(String[] args) {
    WebSocketContainer container = null; //
    Session session = null;
    try {
        //Tyrus is plugged via ServiceLoader API. See notes above
        container = ContainerProvider.getWebSocketContainer();
        //WS1 is the context-root of my web.app 
        //ratesrv is the  path given in the ServerEndPoint annotation on server implementation
        session = container.connectToServer(WSClient.class, URI.create("ws://localhost:8080/WS1/ratesrv"));
        wait4TerminateSignal();
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (session != null) {
            try {
                session.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}

}