入门websocket,用java编写程序,想从服务器接收消息,看了帖子,接收消息用函数public void onMessage(String message, Session session),那么具体应该怎么用到呢,函数接收的参数应该是怎么样的,能不能举例,万望诸位指点
4条回答 默认 最新
- oyljerry 2018-08-09 07:43关注
public class WebSocketTest { @OnMessage public void onMessage(String message, Session session) throws IOException, InterruptedException { // Print the client message for testing purposes System.out.println("Received: " + message); // Send the first message to the client session.getBasicRemote().sendText("This is the first server message"); // Send 3 messages to the client every 5 seconds int sentMessages = 0; while (sentMessages < 3) { Thread.sleep(5000); session.getBasicRemote().sendText("This is an intermediate server message. Count: " + sentMessages); sentMessages++; } // Send a final message to the client session.getBasicRemote().sendText("This is the last server message"); } @OnOpen public void onOpen() { System.out.println("Client connected"); } @OnClose public void onClose() { System.out.println("Connection closed"); } }
本回答被题主选为最佳回答 , 对您是否有帮助呢?解决评论 打赏 举报无用 2