我正在使用Spring websocket支持。我的問題是如何設置websocket連接超時。現在連接在幾分鐘後自動關閉。我想連接永遠不會關閉。春季websocket超時設置
這裏是我的WebSocket處理程序:
public class MyHandler implements WebSocketHandler {
private Logger logger = LoggerFactory.getLogger(this.getClass());
class MyTimerTask extends TimerTask {
private WebSocketSession session;
public MyTimerTask(WebSocketSession session) {
this.session = session;
}
@Override
public void run() {
try {
String msg = ((int)(Math.random()*50)) + "";
this.session.sendMessage(new TextMessage(msg.toString()));
} catch (IOException e) {
e.printStackTrace();
}
}
}
@Autowired
private UserDao userDao;
@Autowired
private JdbcDaoImpl jdbcDaoImpl;
private Timer timer;
@Override
public void afterConnectionEstablished(WebSocketSession session)
throws Exception {
System.out.println("websocket????");
timer = new Timer();
timer.schedule(new MyTimerTask(session), 0, 1000);
logger.info("logger connection");
}
@Override
public void handleMessage(WebSocketSession session,
WebSocketMessage<?> message) throws Exception { }
@Override
public void handleTransportError(WebSocketSession session,
Throwable exception) throws Exception { }
@Override
public void afterConnectionClosed(WebSocketSession session,
CloseStatus closeStatus) throws Exception {
System.out.println("websocket????");
timer.cancel();
}
@Override
public boolean supportsPartialMessages() {
return false;
}
}
我的WebSocket配置:
<websocket:handlers>
<websocket:mapping path="/myHandler" handler="myHandler"/>
</websocket:handlers>
<bean id="myHandler" class="com.sdp.websocket.MyHandler"/>
和JavaScript客戶端:
var webserver = 'ws://localhost:8080/authtest/myHandler';
var websocket = new WebSocket(webserver);
websocket.onopen = function (evt) { onOpen(evt) };
websocket.onclose = function (evt) { onClose(evt) };
websocket.onmessage = function (evt) { onMessage(evt) };
websocket.onerror = function (evt) { onError(evt) };
function onOpen(evt) {
console.log("Connected to WebSocket server.");
}
function onClose(evt) {
console.log("Disconnected");
}
function onMessage(evt) {
console.log('Retrieved data from server: ' + evt.data);
}
function onError(evt) {
console.log('Error occured: ' + evt.data);
}
debugger;
function sendMsg(){
websocket.send("{msg:'hello'}");
}
是的,你是對的。它由Tomcat的會話和cookie超時決定。我在我的web.xml中設置了超時時間 – user3135996 2014-09-22 12:56:12
查看Spring Session(https://github.com/spring-projects/spring-session),它在WebSocket處於活動狀態時保持HttpSession活動 – 2014-09-22 14:48:13
您是否更改'session- Tomcat的web.xml文件中的「超時」來解決這個問題? – 2017-03-06 14:19:44