gpt4 book ai didi

java - spring如何调用websocket服务器向客户端发送消息

转载 作者:搜寻专家 更新时间:2023-11-01 03:56:43 26 4
gpt4 key购买 nike

我的项目使用spring框架

WebSocketConfig.java

@Configuration
@EnableWebMvc
@EnableWebSocket
public class WebSocketConfig extends WebMvcConfigurerAdapter implements WebSocketConfigurer {
@Override
public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
registry.addHandler(systemWebSocketHandler(),"/webSocketServer").addInterceptors(new WebSocketHandshakeInterceptor());

registry.addHandler(systemWebSocketHandler(), "/sockjs/webSocketServer").addInterceptors(new WebSocketHandshakeInterceptor())
.withSockJS();
}

@Bean
public WebSocketHandler systemWebSocketHandler(){
return new SystemWebSocketHandler();
}

}

SystemWebSocketHandler.java

public class SystemWebSocketHandler implements WebSocketHandler {

private static final Logger logger;

private static final ArrayList<WebSocketSession> users;

static {
users = new ArrayList<>();
logger = LoggerFactory.getLogger(SystemWebSocketHandler.class);
}

@Autowired
private WebSocketService webSocketService;

@Override
public void afterConnectionEstablished(WebSocketSession session) throws Exception {
logger.debug("connect to the websocket success......");
users.add(session);
String userName = (String) session.getAttributes().get(Constants.WEBSOCKET_USERNAME);
//查询未读消息
int count = webSocketService.getUnReadNews((String)session.getAttributes().get(Constants.WEBSOCKET_USERNAME));

session.sendMessage(new TextMessage(count+""));
}

@Override
public void handleMessage(WebSocketSession session, WebSocketMessage<?> message) throws Exception {

}

@Override
public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
logger.debug("websocket connection closed......");
users.remove(session);
}

@Override
public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) throws Exception {
logger.debug("websocket connection closed......");
users.remove(session);
}

@Override
public boolean supportsPartialMessages() {
return false;
}

/**
* 给所有在线用户发送消息
*
* @param message
*/
public void sendMessageToUsers(TextMessage message) {
for (WebSocketSession user : users) {
try {
if (user.isOpen()) {
user.sendMessage(message);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}

/**
* 给某个用户发送消息
*
* @param userName
* @param message
*/
public void sendMessageToUser(String userName, TextMessage message) {
for (WebSocketSession user : users) {
if (user.getAttributes().get(Constants.WEBSOCKET_USERNAME).equals(userName)) {
try {
if (user.isOpen()) {
user.sendMessage(message);
}
} catch (IOException e) {
e.printStackTrace();
}
break;
}
}
}
}

我的jsp客户端

if ('WebSocket' in window) {
websocket = new WebSocket("ws://localhost:8080/Origami/webSocketServer");
} else if ('MozWebSocket' in window) {
websocket = new MozWebSocket("ws://localhost:8080/Origami/webSocketServer");
} else {
websocket = new SockJS("http://localhost:8080/Origami/sockjs/webSocketServer");
}

这是我的 websocket 代码,运行良好

现在我想在 Controller 中向客户端发送消息,这是我的 Controller

@Controller
public class AdminController {

static Logger logger = LoggerFactory.getLogger(AdminController.class);

@Autowired(required = false)
private AdminService adminService;

@Autowired(required = false)
private SystemWebSocketHandler systemWebSocketHandler;

@RequestMapping("/auditing")
@ResponseBody
public String auditing(HttpServletRequest request){
String result = "fail";
int id = Integer.parseInt(request.getParameter("id"));
String reason = request.getParameter("reason");
String title = request.getParameter("title");
String username = request.getParameter("username");
News news = new News();
DateTime dateTime = DateTime.now();
news.setNewsTime(dateTime.toDate());
news.setState(0);
news.setUsername(username);
if(reason.equals("")){
result = adminService.auditingById(id,"Y");
news.setNewsContent(String.format(Constants.AUDIT_MESSAGE, username, title, reason));
adminService.addNewsWithUnAudit(news);
}else{
news.setNewsContent(String.format(Constants.UN_AUDIT_MESSAGE,username,title,reason));
result = adminService.addNewsWithUnAudit(news);
result = adminService.auditingById(id, "D");
}
//SystemServerEndPoint serverEndPoint = new SystemServerEndPoint();
int unReadNewsCount = adminService.getUnReadNews(username);
systemWebSocketHandler.sendMessageToUser(username, new TextMessage(unReadNewsCount + ""));
return result;
}
}

我要打电话

systemWebSocketHandler.sendMessageToUser(username, new TextMessage(unReadNewsCount + ""));

向客户端发送消息但systemWebSocketHandler为空

如何将systemWebSocketHandler注入(inject) Controller 或其他一些想法来完成所需的?比如服务器需要向客户端发送消息时连接到websocketserver,完成后关闭

我的英语很差,但我正在努力学习

最佳答案

我已经解决了这个问题

@Controller
public class AdminController {

@Bean
public SystemWebSocketHandler systemWebSocketHandler() {
return new SystemWebSocketHandler();
}

关于java - spring如何调用websocket服务器向客户端发送消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25375152/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com