错误的截图:
在WebSocketService(你的不一定是这个名字,就是websocket的实现类) 这里截取了部门代码,主要就是针对sendObject产生的异常问题的处理
/**
* 向指定客户端发送消息(对象的形式)
* @param userName
* @param object
*/
public static void sendMessage(String userName,Object object){
try {
WebSocketClient webSocketClient = webSocketMap.get(userName);
if(webSocketClient!=null){
webSocketClient.getSession().getBasicRemote().sendObject(object);
}
} catch (IOException | EncodeException e) {
e.printStackTrace();
throw new RuntimeException(e.getMessage());
}
}
根据上面提示的信息没有为map对象指定一个编码器,我们需要在@ServerEndpoint
注解后面添加一个指定的编码器,@ServerEndpoint(value = "/websocket/{userName}",encoders = {ServerEncoder.class})
ServerEncoder是我们自己写的一个编码器,我将代码放到下面
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.websocket.EncodeException;
import javax.websocket.Encoder;
import javax.websocket.EndpointConfig;
import java.util.HashMap;
/**
* @desc: WebSocket编码器
* @author: LiuCh
* @since: 2021/8/18
*/
public class ServerEncoder implements Encoder.Text<HashMap> {
private static final Logger log = LoggerFactory.getLogger(ServerEncoder.class);
/**
* 这里的参数 hashMap 要和 Encoder.Text<T>保持一致
* @param hashMap
* @return
* @throws EncodeException
*/
@Override
public String encode(HashMap hashMap) throws EncodeException {
/*
* 这里是重点,只需要返回Object序列化后的json字符串就行
* 你也可以使用gosn,fastJson来序列化。
* 这里我使用fastjson
*/
try {
return JSONObject.toJSONString(hashMap);
}catch (Exception e){
log.error("",e);
}
return null;
}
@Override
public void init(EndpointConfig endpointConfig) {
//可忽略
}
@Override
public void destroy() {
//可忽略
}
}
在业务中的操作
Map<String, Object> result = new HashMap<>(2); //返回的结果对象
result.put("type","add");
result.put("message","1");
WebSocketService.sendMessage(接收的账号, result);
感谢 https://blog.csdn.net/weixin_34050389/article/details/92259197