簡體   English   中英

Lambda在Websocket會話中不起作用

[英]Lambda Does Not Work In Websocket Session

我剛遇到一個奇怪的小問題:

javax.websocket.Session session = //...
// this works
newSession.addMessageHandler(new MessageHandler.Whole<String>() {

    @Override
    public void onMessage(String message) {
        MyWebSocket.this.onMessage(message);
    }
});
// these don't work
newSession.addMessageHandler((MessageHandler.Whole<String>) MyWebSocket.this::onMessage);
newSession.addMessageHandler((MessageHandler.Whole<String>) message -> MyWebSocket.this.onMessage(message));


void onMessage(String message) {
    System.out.println(message);
}

有人知道為什么lambda表達式在這個實例中不起作用嗎? 沒有編譯錯誤,沒有異常,沒有任何東西。 沒有調用方法''onMessage''。

我使用Java 1.8.0_65和Tyrus參考實現1.9。

請參閱https://blogs.oracle.com/PavelBucek/entry/websocket_api_1_1_leleased

tldr; 你必須使用Session#addMessageHandler(Class<T> clazz, MessageHandler.Whole<T> handler)

/**
* Register to handle to incoming messages in this conversation. A maximum of one message handler per
* native websocket message type (text, binary, pong) may be added to each Session. I.e. a maximum
* of one message handler to handle incoming text messages a maximum of one message handler for
* handling incoming binary messages, and a maximum of one for handling incoming pong
* messages. For further details of which message handlers handle which of the native websocket
* message types please see {@link MessageHandler.Whole} and {@link MessageHandler.Partial}.
* Adding more than one of any one type will result in a runtime exception.
*
* @param clazz   type of the message processed by message handler to be registered.
* @param handler whole message handler to be added.
* @throws IllegalStateException if there is already a MessageHandler registered for the same native
*                               websocket message type as this handler.
*/
public void addMessageHandler(Class<T> clazz, MessageHandler.Whole<T> handler);

為了使用lambdas作為消息處理程序。

根據我的理解, MessageHandler需要是一個@FunctionalInterface來允許lambda表達式,但事實並非如此。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM