websocket
websocket代码,包含service的注入及测试
package com.example.testmabatusplus.ws;
import com.example.testmabatusplus.bo.User;
import com.example.testmabatusplus.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.List;
@Component
@ServerEndpoint("/websocketTest/{userId}")
public class TestWebSocket {
private static UserService userService;
@Autowired
public void setUserService(UserService userService){
this.userService = userService;
}
private Logger logger = LoggerFactory.getLogger(TestWebSocket.class);
private String userId;
@OnOpen
public void onOpen(@PathParam("userId") String userId, Session session) throws IOException {
this.userId = userId;
logger.debug("新连接:{}",userId);
System.out.println("新连接:{}"+"------"+userId);
}
@OnClose
public void onClose(){
logger.debug("连接:{} 关闭",this.userId);
}
@OnMessage
public void onMessage(String message, Session session) throws IOException {
List<User> list = userService.list(null);
session.getBasicRemote().sendText("total ===" + list.size() + session.getId());
}
@OnError
public void onError(Session session, Throwable error){
logger.debug("用户id为:{}的连接发送错误",this.userId);
error.printStackTrace();
}
}
测试
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
websocket Demo <br />
<input id="text" type="text" />
<button onclick="send()"> Send </button>
<button onclick="closeWebSocket()"> Close </button>
<div id="message"> </div>
<script type="text/javascript">
if('WebSocket' in window){
websocket = new WebSocket("ws://localhost:8080/websocketTest/1");
console.log("link success")
}else{
alert('Not support websocket')
}
websocket.onerror = function(){
setMessageInnerHTML("error");
};
websocket.onopen = function(event){
setMessageInnerHTML("open");
}
console.log("-----")
websocket.onmessage = function(event){
setMessageInnerHTML(event.data);
}
websocket.onclose = function(){
setMessageInnerHTML("close");
}
window.onbeforeunload = function(){
websocket.close();
}
function setMessageInnerHTML(innerHTML){
document.getElementById('message').innerHTML += innerHTML + '<br/>';
}
function closeWebSocket(){
websocket.close();
}
function send(){
var message = document.getElementById('text').value;
websocket.send(message);
}
</script>
</body>
</html>