特别說明:自學筆記
使用websocket有兩種方式:
- 使用sockjs,
- 使用h5的标準。
使用Html5标準自然更友善簡單,是以記錄的是配合h5的使用方法。
1、pom.xml中添加如下:
核心是@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>1.3.5.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的具體實作類,很簡單,直接上代碼:
package com.reapal.websocket;
import org.springframework.stereotype.Component;
import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.concurrent.atomic.AtomicInteger;
/**
* @author jackcooper
* @create 2017-12-28 13:04
*/
@ServerEndpoint(value = "/websocket")
@Component
public class ApplicationWebSocket {
//靜态變量,用來記錄目前線上連接配接數。設計成線程安全的。
private static AtomicInteger onlineCount = new AtomicInteger(0);
//concurrent包的線程安全Set,用來存放每個用戶端對應的ApplicationWebSocket對象。
private static CopyOnWriteArraySet<ApplicationWebSocket> webSocketSet = new CopyOnWriteArraySet<ApplicationWebSocket>();
//與某個用戶端的連接配接會話,需要通過它來給用戶端發送資料
private Session session;
/**
* 連接配接建立成功調用的方法*/
@OnOpen
public void onOpen(Session session) {
this.session = session;
webSocketSet.add(this); //加入set中
addOnlineCount(); //線上數加1
System.out.println("有新連接配接加入!目前線上人數為" + getOnlineCount());
try {
sendMessage("目前線上人數為:"+getOnlineCount());
} catch (IOException e) {
System.out.println("IO異常");
}
}
/**
* 連接配接關閉調用的方法
*/
@OnClose
public void onClose() {
webSocketSet.remove(this); //從set中删除
subOnlineCount(); //線上數減1
System.out.println("有一連接配接關閉!目前線上人數為" + getOnlineCount());
}
/**
* 收到用戶端消息後調用的方法
*
* @param message 用戶端發送過來的消息*/
@OnMessage
public void onMessage(String message, Session session) {
System.out.println("來自用戶端的消息:" + message);
//群發消息
for (ApplicationWebSocket item : webSocketSet) {
try {
item.sendMessage(message);
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 發生錯誤時調用
@OnError
*/
public void onError(Session session, Throwable error) {
System.out.println("發生錯誤");
error.printStackTrace();
}
public void sendMessage(String message) throws IOException {
//getBasicRemote是阻塞式的
this.session.getBasicRemote().sendText(message);
//非阻塞式的
// this.session.getAsyncRemote().sendText(message);
}
/**
* 群發自定義消息
* */
public static void sendInfo(String message) throws IOException {
for (ApplicationWebSocket item : webSocketSet) {
try {
item.sendMessage(message);
} catch (IOException e) {
continue;
}
}
}
public static synchronized int getOnlineCount() {
return onlineCount.get();
}
public static synchronized void addOnlineCount() {
ApplicationWebSocket.onlineCount.getAndIncrement();
}
public static synchronized void subOnlineCount() {
ApplicationWebSocket.onlineCount.getAndDecrement();
}
}
使用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:8084/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>
4、總結
springboot已經做了深度的內建和優化,要注意是否添加了不需要的依賴、配置或聲明。由于很多講解元件使用的文章是和spring內建的,會有一些配置,在使用springboot時,由于springboot已經有了自己的配置,再這些配置有可能導緻各種各樣的異常。
spring boot內建WebSocket實時輸出日志到web頁面