WebSocket @OnMessage
时间: 2023-12-21 13:58:17 浏览: 48
The @OnMessage annotation is used in WebSocket programming to indicate that a method in a class should be invoked when a message is received from the client.
Syntax:
```java
@OnMessage
public void methodName(Session session, String message) {
// code to handle received message
}
```
Here, the method marked with @OnMessage takes two parameters: the WebSocket session object and the message received from the client. The method body can contain any logic to process the message.
For example, the following code snippet shows how to implement a WebSocket endpoint that echoes back any messages it receives from the client:
```java
import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
@ServerEndpoint(value = "/echo")
public class EchoEndpoint {
@OnMessage
public void onMessage(Session session, String message) throws Exception {
session.getBasicRemote().sendText(message);
}
}
```
In this example, the WebSocket endpoint is mapped to the "/echo" URI. The onMessage() method simply sends back the received message to the client using the session's getBasicRemote() method.
Note that the @OnMessage annotation can also be used with other data types besides String, such as ByteBuffer, InputStream, and Reader.
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)