當我們在服務端使用WebSocket的sendObject方法直接向前端傳遞一個物件時,會有如下報錯
javax.websocket.EncodeException: No encoder specified for object of class [這里是你sendObject里傳的物件的全名]
原因是你沒有在@ServerEndpoint里指定Websocket的編碼器,解決方法如下:
撰寫一個編碼器類,下面是一個比較通用的編碼器,你可以直接復制粘貼然后進行簡單的修改就好,注解也很詳細,
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.json.JsonMapper;
import javax.websocket.EncodeException;
import javax.websocket.Encoder;
import javax.websocket.EndpointConfig;
/*
* Text<ResponseMessage>里的ResponseMessage是我自己寫的一個訊息類
* 如果你寫了一個名叫Student的類,需要通過sendObject()方法發送,那么這里就是Text<Student>
*/
public class ServerEncoder implements Encoder.Text<ResponseMessage> {
@Override
public void destroy() {
// TODO Auto-generated method stub
// 這里不重要
}
@Override
public void init(EndpointConfig arg0) {
// TODO Auto-generated method stub
// 這里也不重要
}
/*
* encode()方法里的引數和Text<T>里的T一致,如果你是Student,這里就是encode(Student student)
*/
@Override
public String encode(ResponseMessage responseMessage) throws EncodeException {
try {
/*
* 這里是重點,只需要回傳Object序列化后的json字串就行
* 你也可以使用gosn,fastJson來序列化,
*/
JsonMapper jsonMapper = new JsonMapper();
return jsonMapper.writeValueAsString(responseMessage);
} catch ( JsonProcessingException e) {
e.printStackTrace();
return null;
}
}
}
然后在@ServerEndpoint注解的類中指定encoders
/*
*這里的ServerEncoder就是上面的編碼器類
*/
@ServerEndpoint(value = "/chat/{room}",encoders = { ServerEncoder.class })
@Component
public class WebSocketService {
// 你的代碼
}
如果你要傳遞多種型別的物件,也可以撰寫多個編碼器,然后在endocer里添加多個,
如果你有興趣,可以來我的博客逛逛
https://timegoesby.top/
本文章參考自下面這篇文章
https://blog.csdn.net/u014175572/article/details/46490395
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/291995.html
標籤:其他
上一篇:Docker + Nginx + PHP 訪問403,404問題
下一篇:Centos安裝Nginx
