因为最近一个项目中要使用常练接的问题 要求是使用spring中的websocket 但是 亲们 你们知道吗? spring中websocket是一个深坑呀~ 太坑了
所以整理了一下 关于spring-websocket的相关问题 防止以后忘记了~~~~~~~ 啊哈哈
步骤:
1、将websocket-config注入到spring中
2、将websocket配置的链接注入到
websocket-config中
3、编写相关的业务逻辑
WebSocket-Configer
package com.keepalive.controller;
import org.springframework.context.annotation.Bean;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;
import org.springframework.web.socket.server.standard.ServerEndpointRegistration;
import com.gateguard.keepalive.service.CaseEndPointService;
public class WebSocketConfiger
{
@Bean
public ServerEndpointExporter endpointExporter(){
return new ServerEndpointExporter();
}
/**
* 绑定webSocket的链接和实现类
* @return
*/
@Bean
public ServerEndpointRegistration caseCount()
{
System.out.println("caseCount");
return new ServerEndpointRegistration("/casecount", CaseCountEndPoint.class);
}
/**
* 绑定webSocket的链接 主要是单例模式
* @return
*/
@Bean
public ServerEndpointRegistration caseCountSingle()
{
System.out.println("caseCountSingle");
return new ServerEndpointRegistration("/casecountsingle", new CaseCountEndPoint(caseEndPointService()));
}
@Bean
public CaseEndPointService caseEndPointService() {
return new CaseEndPointService();
}
}
<beans:bean id="websocket" class="com.keepalive.controller.WebSocketConfiger">
package com.keepalive.controller;
import java.io.IOException;
import javax.websocket.Endpoint;
import javax.websocket.EndpointConfig;
import javax.websocket.MessageHandler;
import javax.websocket.Session;
import org.springframework.beans.factory.annotation.Autowired;
import com.gateguard.keepalive.service.CaseEndPointService;
public class CaseCountEndPoint extends Endpoint
{
private final CaseEndPointService caseEndPointService;//这里 final必须添加
@Autowired
public CaseCountEndPoint(CaseEndPointService caseEndPointService) {
this.caseEndPointService = caseEndPointService;
}
@Override
public void onOpen(final Session session, EndpointConfig endpointConfig) {
System.out.println("进入 webSocket onOpen");
session.addMessageHandler(new MessageHandler.Whole<String>() {
@Override
public void onMessage(String message) {
System.out.println("接受信息"+message);
try {
session.getBasicRemote().sendText(String.valueOf(caseEndPointService.getCount()));
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
}
package com.keepalive.service;
public class CaseEndPointService
{
public double getCount()
{
return Math.random();
}
}
jsp:
使用lib文件:spring-websocket-4.0.0.RELEASE.jar