此篇文章主要写的我们在springCloud中使用websocket时,接收端写的主要代码。
此篇是小白看的。并详细介绍了应该怎样测试websocket的接收。
以及如果我们需要有自己写的service注入时,在websocket中应该怎样注入。此处我注入的service是deviceService。
java
import com.apex.iot.device.service.DeviceService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.util.HashMap;
import java.util.Map;
@Slf4j
@Component
@ServerEndpoint("/iotDataWebsocket")
public class DataWebSocketService {
private static Map<String,Session> sessionPool = new HashMap<String,Session>();
// 我们自己写的service不能直接注入,需要这样注入
private static DeviceService deviceService;
@Autowired
public void setDeviceService(DeviceService deviceService) {
this.deviceService = deviceService;
}
/**
* 连接建立成功调用的方法
*/
@OnOpen
public void onOpen(Session session) {
log.info("连接成功:{}", session.getId());
sessionPool.put(session.getId(), session);
}
/**
* 连接关闭调用的方法
* @param session
*/
@OnClose
public void onClose(Session session) {
String sessionId = session.getId();
sessionPool.remove(sessionId);
}
/**
* 收到客户端消息后调用的方法
* @param message 客户端发送过来的消息
*/
@OnMessage
public synchronized void onMessage(String message, Session session) {
log.info("服务端收到客户端[{}]的消息:{}", session.getId(), message);
try{
System.out.println(message);
this.sendMessage(session.getId(), message);
}catch (Exception e) {
log.error("处理消息失败!服务端收到客户端[{}]的消息:{}", session.getId(), message);
}
}
/**
* 发生错误时调用
*/
@OnError
public void onError(Session session, Throwable error) {
System.out.println("发生错误");
error.printStackTrace();
}
/**
* 发送消息
* @param sessionId
* @param message
*/
public void sendMessage(String sessionId, String message) {
Session session = sessionPool.get(sessionId);
if(session != null) {
synchronized (session) {
try{
// 你自己的方法
String result = deviceService.getDeviceMsgByRedis(message);
session.getBasicRemote().sendText(result);
}catch (Exception e) {
e.printStackTrace();
log.error("发送消息失败!", e);
}
}
}else{
log.error("没有找到sessionId:{}", sessionId);
}
}
}
应该怎样测试:
给大家两个链接,都是进行测试websocket的。因为我这边洗的都是后台,所以直接用网页进行测试:
java
https://wstool.jackxiang.com/
http://websocket-test.com/
我用的最多的是第一个链接:https://wstool.jackxiang.com/
链接里是我们的服务器地址,比如我写的是
ws://localhost:30116/iotDataWebsocket
其中iotDataWebsocket是我们在websocket中定义的,就是在类上的@ServerEndpoint("/iotDataWebsocket")
这时候我们有时候会出现连接不上的问题。没关系,更改一下配置:
我们在application.yml中添加
java
server:
port: 30116
# ignored-urls: /**/**
ignored-urls: /iotDataWebsocket,/device/save,/device/getDeviceMsgById
在ignored-urls中,我们这几个方法可以直接通过网页访问
以上准备工作完成了,就可以进行测试了
我们点击测试工具的开启连接,出现open这一行绿色的字,就说明连接成功,
点击开始发送按钮,即可进行websocket的发送。当我们看到收到消息的时候,websocket的联调成功了。