在程序中创建一个简单的websocket,在哪里调用onOpen方法?

时间:2015-07-07 17:35:48

标签: java websocket

我找到了一个代码来创建一个简单的websocket连接。 在main函数中,只调用了WebsocketClientEndpoint的构造函数,并且我没有在构造函数中看到对onOpen函数的调用。在输出中," 打开websocket "按照onOpen功能中的指定打印。任何人都可以告诉我onOpen函数的调用在哪里?

TestApp.java:

package testapp;

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("wss://real.okcoin.cn:10440/websocket/okcoinapi"));

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

        // send message to websocket
        clientEndPoint.sendMessage("{'event':'addChannel','channel':'ok_btccny_ticker'}");

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

}

WebsocketClientEndpoint.java

package testapp;

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;

 /**
 * ChatServer Client
 *
 * @author Jiji_Sasidharan
 */
@ClientEndpoint
public 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 message
 */
public void addMessageHandler(MessageHandler msgHandler) {
    this.messageHandler = msgHandler;
}

/**
 * Send a message.
 *
 * @param user
 * @param message
 */
public void sendMessage(String message) {
    this.userSession.getAsyncRemote().sendText(message);
}

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

    public void handleMessage(String message);
}
}

2 个答案:

答案 0 :(得分:1)

您必须阅读注释如何理解这一点。@OnOpen是一个注释。 @OnOpen允许我们拦截新会话的创建。

注释类型OnOpen

  

@Retention(值= RUNTIME)
  @target(值= METHOD)
  public @interface OnOpen

     

此方法级别注释可用于装饰Java方法   希望在新的Web套接字会话打开时调用。

     

该方法只能采用以下参数: -

     

可选的Session参数
    可选的EndpointConfig参数
    使用PathParam注释注释的零到n字符串参数。

     

参数可以按任何顺序出现。

答案 1 :(得分:0)

当您的WebsocketClientEndpoint构造函数被调用时,它将尝试打开与位于endPointURI的websocket服务器的连接,并通过编写@clientEndPoint注释扩展EndPoint类。因此,将根据从服务器接收的信号调用@OnOpen@OnMessageOnClose等所有注释。因此,当自动打开连接时,将调用用@OnOpen注释的函数。