关于websocket编程过程中遇到的问题 5C

入门websocket,用java编写程序,想从服务器接收消息,看了帖子,接收消息用函数public void onMessage(String message, Session session),那么具体应该怎么用到呢,函数接收的参数应该是怎么样的,能不能举例,万望诸位指点

4个回答

这个是回调函数,在继承的类中实现就可以了

 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");
    }
}

package com.ia.lhc.websocket;

import java.io.IOException;
import java.util.ArrayList;
import java.util.concurrent.locks.ReentrantLock;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.WebSocketMessage;
import org.springframework.web.socket.WebSocketSession;

import com.ia.lhc.model.User;

@Component
public class MsgScoketHandle implements WebSocketHandler {

/**已经连接的用户*/
private static final ArrayList<WebSocketSession> users;
private static final ReentrantLock lock = new ReentrantLock();
private Logger logger = Logger.getLogger(this.getClass().getName()); 
static {
    //保存当前连接用户
    users = new ArrayList<WebSocketSession>();
}

/**
 * 建立链接
 * @param webSocketSession
 * @throws Exception
 */
@Override
public void afterConnectionEstablished(WebSocketSession webSocketSession) throws Exception {
    //将用户信息添加到list中
    users.add(webSocketSession);
    logger.warn("WebSocket建立连接成功");
    User user  = (User) webSocketSession.getAttributes().get("user");
    if(user != null){
        logger.warn("当前连接用户: "+user.getUsername());
    }
    logger.warn("webSocket连接数量:"+users.size());
}

/**
 * 接收消息
 * @param webSocketSession
 * @param webSocketMessage
 * @throws Exception
 */
@Override
public void handleMessage(WebSocketSession webSocketSession, WebSocketMessage<?> webSocketMessage) throws Exception {
    User user = (User) webSocketSession.getAttributes().get("user");
    logger.info("收到用户:"+user.getUsername()+"的消息");
    logger.info(webSocketMessage.getPayload().toString());
}

/**
 * 异常处理
 * @param webSocketSession
 * @param throwable
 * @throws Exception
 */
@Override
public void handleTransportError(WebSocketSession webSocketSession, Throwable throwable){
    if (webSocketSession.isOpen()){
        //关闭session
        try {
            webSocketSession.close();
        } catch (IOException e) {
        }
    }
    //移除用户
    if(users.size()>0)
    {
        users.remove(webSocketSession);
        User user = (User) webSocketSession.getAttributes().get("user");
        logger.warn(user.getUsername()+":断开websocket连接");
        logger.warn("webSocket当前连接数量:"+users.size());
    }
}

/**
 * 断开链接
 * @param webSocketSession
 * @param closeStatus
 * @throws Exception
 */
@Override
public void afterConnectionClosed(WebSocketSession webSocketSession, CloseStatus closeStatus) throws Exception {

    if(users.size()>0)
    {
        users.remove(webSocketSession);
        User user = (User) webSocketSession.getAttributes().get("user");
        logger.warn(user.getUsername()+":断开websocket连接");
        logger.warn("webSocket当前连接数量:"+users.size());
    }
}

@Override
public boolean supportsPartialMessages() {
    return false;
}

/**
 * 发送消息给指定的用户
 * @param user
 * @param messageInfo
 */
public void sendMessageToUser(String userId, String message){

    TextMessage messageInfo = new TextMessage(message);
    for (WebSocketSession session : users) {
        User sessionUser = (User) session.getAttributes().get("user");
        //根据用户ID去判断用户接收消息的用户
        if(userId.equals(sessionUser.getUserid())){
            try {
                if (session.isOpen()){
                    session.sendMessage(messageInfo);
                    logger.warn("发送消息给:"+userId+"内容:"+messageInfo);
                }
                break;
            } catch (IOException e) {
                e.printStackTrace();
                logger.error(e);
            }
        }else{
            logger.warn(userId+"未登录,无法发送socket");
        }
    }
}

}


Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!