错误的截图: 在WebSocketService(你的不一定是这个名字,就是websocket的实现类) 这里截取了部门代码,主要就是针对sendObject产生的异常问题的处理
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;
public class ServerEncoder implements Encoder.Text<HashMap> {
private static final Logger log = LoggerFactory.getLogger(ServerEncoder.class);
@Override
public String encode(HashMap hashMap) throws EncodeException {
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
|