本文主要解决的是Spring WebSocket无法注入,或者是声明的web socket前端无法获取到,WebSocket
因此本文使用的是Java WebSocket 结合Spring的配置来进行消息传输
后端
@ServerEndpoint(value="/websocketDemo/press.do",configurator = SpringConfigurator.class)
public class WebsocketDemo {
private static final Set<WebsocketDemo> connections = new CopyOnWriteArraySet<>();
private String nickname;
private Session session;
@Override
public int hashCode() {
// TODO Auto-generated method stub
return super.hashCode();
}
@Override
public boolean equals(Object obj) {
// TODO Auto-generated method stub
return super.equals(obj);
}
@OnOpen
public void start(Session session) {
this.session = session;
connections.add(this);
String msg = "NAME" + "\t" + nickname;
try {
this.session.getBasicRemote().sendText(msg);
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("连接数量:"+connections.size());
}
@OnClose
public void end() {
connections.remove(this);
String message = String.format("* %s %s",
nickname, "has disconnected.");
broadcast(message);
System.out.println(nickname+" 关闭");
}
@OnMessage
public void incoming(String message) {
// Never trust the client
String filteredMessage = String.format("%s: %s",
nickname, HTMLFilter.filter(message.toString()));
System.out.println("filteredMessage:"+filteredMessage);
broadcast(message);
}
@OnError
public void onError(Throwable t) throws Throwable {
}
public void broadcast(String msg) {
for(WebsocketDemo user:connections){
try {
user.session.getBasicRemote().sendText(msg);
} catch (IOException e) {
e.printStackTrace();
}
}
}
直接调用broadcast进行消息广播
前端
前端接收广播消息
var host =window.location.host;
if ('WebSocket' in window) {
websocket = new WebSocket("ws://localhost:8080/web/websocketDemo/press.do");
} else if ('MozWebSocket' in window) {
websocket = new MozWebSocket("ws://localhost:8080/web/websocketDemo/press.do");
} else {
websocket = new SockJS("http://localhost:8080/web/websocketDemo/press.do");
}
websocket.onopen = function (evnt) {
console.log("开启socket");
};
websocket.onmessage = function (evnt) {
//确认按键 od
if(evnt.data == "0d"){
block();
}
else if(evnt.data == "1b"){
//取消按键 1b
console.log("cancel");
}else if(evnt.data == "2a"){
console.log("*");
//正常数字 2a
}else if(evnt.data =="08"){
console.log("delete");
//更正数字 08
}else if(evnt.data =="80"){
//超时数字 80 超时之后再次调用启动加密接口即可重新输入密码
eject();
}
};
websocket.onerror = function (evnt) {
console.log("发生错误");
};
websocket.onclose = function (evnt) {
console.log("关闭");
}