使用websocket有兩種方式:1是使用sockjs,2是使用h5的標准。使用Html5標准自然更方便簡單,所以記錄的是配合h5的使用方法。
1、pom
核心是@ServerEndpoint這個注解。這個注解是Javaee標准里的注解,tomcat7以上已經對其進行了實現,如果是用傳統方法使用tomcat發布項目,只要在pom文件中引入javaee標准即可使用。
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-api</artifactId>
<version>7.0</version>
<scope>provided</scope>
</dependency>
但使用springboot的內置tomcat時,就不需要引入javaee-api了,spring-boot已經包含了。使用springboot的websocket功能首先引入springboot組件。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
<version>2.1.4.RELEASE</version>
</dependency>
順便說一句,springboot的高級組件會自動引用基礎的組件,像spring-boot-starter-websocket就引入了spring-boot-starter-web和spring-boot-starter,所以不要重復引入。
2、使用@ServerEndpoint創立websocket endpoint
首先要注入ServerEndpointExporter,這個bean會自動注冊使用了@ServerEndpoint注解聲明的Websocket endpoint。要注意,如果使用獨立的servlet容器,而不是直接使用springboot的內置容器,就不要注入ServerEndpointExporter,因為它將由容器自己提供和管理。
@Configuration
public class WebSocketConfig {
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
}
接下來就是寫websocket的具體實現類,很簡單,直接上代碼:
@Component
@ServerEndpoint(value = "/websocket")
public class MyWebSocket {
// concurrent包的線程安全Set,用來存放每個客戶端對應的MyWebSocket對象。
private static CopyOnWriteArraySet<MyWebSocket> webSocketSet = new CopyOnWriteArraySet<MyWebSocket>();
//與某個客戶端的連接會話,需要通過它來給客戶端發送數據
private Session session;
/**
* 連接建立成功調用的方法
*
* @param session
*/
@OnOpen
public void onOpen(Session session) {
this.session = session;
webSocketSet.add(this); //加入set中
System.out.println("有新連接加入!當前在線人數為" + webSocketSet.size());
try {
sendMessage("連接成功,當前時間:" + new java.sql.Timestamp(System.currentTimeMillis()));
} catch (IOException e) {
System.out.println("IO異常");
}
}
/**
* 連接關閉調用的方法
*/
@OnClose
public void onClose() {
// 從set中刪除
webSocketSet.remove(this);
System.out.println("有一連接關閉!當前在線人數為" + webSocketSet.size());
}
/**
* 收到客戶端消息后調用的方法
*
* @param message 客戶端發送過來的消息
*/
@OnMessage
public void onMessage(String message, Session session) {
System.out.println("來自客戶端的消息:" + message);
// 群發消息
for (MyWebSocket item : webSocketSet) {
try {
item.sendMessage(message);
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 發生錯誤時調用
*
* @param session
* @param error
*/
@OnError
public void onError(Session session, Throwable error) {
System.out.println("發生錯誤");
error.printStackTrace();
}
/**
* 發送消息
*
* @param message
* @throws IOException
*/
public void sendMessage(String message) throws IOException {
this.session.getBasicRemote().sendText(message);
// this.session.getAsyncRemote().sendText(message);
}
/**
* 群發自定義消息
*/
public static void sendInfo(String message) throws IOException {
for (MyWebSocket item : webSocketSet) {
try {
item.sendMessage(message);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
使用springboot的唯一區別是要@Component聲明下,而使用獨立容器是由容器自己管理websocket的,但在springboot中連容器都是spring管理的。
雖然@Component默認是單例模式的,但springboot還是會為每個websocket連接初始化一個bean,所以可以用一個靜態set保存起來。
3、前端代碼
<!DOCTYPE HTML>
<html>
<head>
<title>My WebSocket</title>
</head>
<body>
Welcome<br/>
<input id="text" type="text" /><button onclick="send()">Send</button> <button onclick="closeWebSocket()">Close</button>
<div id="message">
</div>
</body>
<script type="text/javascript">
var websocket = null;
//判斷當前瀏覽器是否支持WebSocket
if('WebSocket' in window){
websocket = new WebSocket("ws://localhost:8080/websocket");
}
else{
alert('Not support websocket')
}
//連接發生錯誤的回調方法
websocket.onerror = function(){
setMessageInnerHTML("error");
};
//連接成功建立的回調方法
websocket.onopen = function(event){
setMessageInnerHTML("open");
}
//接收到消息的回調方法
websocket.onmessage = function(event){
setMessageInnerHTML(event.data);
}
//連接關閉的回調方法
websocket.onclose = function(){
setMessageInnerHTML("close");
}
//監聽窗口關閉事件,當窗口關閉時,主動去關閉websocket連接,防止連接還沒斷開就關閉窗口,server端會拋異常。
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>
</html>