認(rèn)識HTML5的WebSocket
WebSocket是HTML5開始提供的一種在單個 TCP 連接上進(jìn)行全雙工通訊的協(xié)議堤框。
在WebSocket API中栖榨,瀏覽器和服務(wù)器只需要做一個握手的動作自沧,然后坟奥,瀏覽器和服務(wù)器之間就形成了一條快速通道树瞭。兩者之間就直接可以數(shù)據(jù)互相傳送。
瀏覽器通過 JavaScript 向服務(wù)器發(fā)出建立 WebSocket 連接的請求爱谁,連接建立以后晒喷,客戶端和服務(wù)器端就可以通過 TCP 連接直接交換數(shù)據(jù)。
當(dāng)你獲取 Web Socket 連接后访敌,你可以通過 send() 方法來向服務(wù)器發(fā)送數(shù)據(jù)凉敲,并通過 onmessage 事件來接收服務(wù)器返回的數(shù)據(jù)。
引入websocket依賴寺旺,核心包
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
配置bean爷抓,名為ServerEndpointExporter
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;
@Configuration
public class WebSocketConfig {
@Bean
public ServerEndpointExporter serverEndpointExporter (){
return new ServerEndpointExporter();
}
}
websocket簡單的例子
import java.io.IOException;
import java.util.concurrent.CopyOnWriteArraySet;
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import org.springframework.stereotype.Component;
/**
* @ServerEndpoint 注解是一個類層次的注解,它的功能主要是將目前的類定義成一個websocket服務(wù)器端,
* 注解的值將被用于監(jiān)聽用戶連接的終端訪問URL地址,客戶端可以通過這個URL來連接到WebSocket服務(wù)器端
* @describe 描述:
* @author 作者:內(nèi)酷拉拉
* @time 創(chuàng)建時間:2017年8月16日 下午3:21:20
*/
@ServerEndpoint("/mywebsocket")
@Component
public class WebSocketTest {
//靜態(tài)變量阻塑,用來記錄當(dāng)前在線連接數(shù)蓝撇。應(yīng)該把它設(shè)計成線程安全的。
private static int onlineCount = 0;
//concurrent包的線程安全Set陈莽,用來存放每個客戶端對應(yīng)的MyWebSocket對象渤昌。若要實現(xiàn)服務(wù)端與單一客戶端通信的話,可以使用Map來存放走搁,其中Key可以為用戶標(biāo)識
private static CopyOnWriteArraySet<WebSocketTest> webSocketSet = new CopyOnWriteArraySet<WebSocketTest>();
//與某個客戶端的連接會話独柑,需要通過它來給客戶端發(fā)送數(shù)據(jù)
private Session session;
/**
* 連接建立成功調(diào)用的方法
* @param session 可選的參數(shù)。session為與某個客戶端的連接會話朱盐,需要通過它來給客戶端發(fā)送數(shù)據(jù)
*/
@OnOpen
public void onOpen(Session session){
this.session = session;
webSocketSet.add(this); //加入set中
addOnlineCount(); //在線數(shù)加
System.out.println("有新連接加入群嗤!當(dāng)前在線人數(shù)為" + getOnlineCount());
}
/**
* 連接關(guān)閉調(diào)用的方法
*/
@OnClose
public void onClose(){
webSocketSet.remove(this); //從set中刪除
subOnlineCount(); //在線數(shù)減
System.out.println("有一連接關(guān)閉菠隆!當(dāng)前在線人數(shù)為" + getOnlineCount());
}
/**
* 收到客戶端消息后調(diào)用的方法
* @param message 客戶端發(fā)送過來的消息
* @param session 可選的參數(shù)
*/
@OnMessage
public void onMessage(String message, Session session) {
System.out.println("來自客戶端的消息:" + message);
//群發(fā)消息
for(WebSocketTest item: webSocketSet){
try {
item.sendMessage(message);
} catch (IOException e) {
e.printStackTrace();
continue;
}
}
}
/**
* 發(fā)生錯誤時調(diào)用
* @param session
* @param error
*/
@OnError
public void onError(Session session, Throwable error){
System.out.println("發(fā)生錯誤");
error.printStackTrace();
}
/**
* 這個方法與上面幾個方法不一樣兵琳。沒有用注解,是根據(jù)自己需要添加的方法骇径。
* @param message
* @throws IOException
*/
public void sendMessage(String message) throws IOException{
this.session.getBasicRemote().sendText(message);
//this.session.getAsyncRemote().sendText(message);
}
public static synchronized int getOnlineCount() {
return onlineCount;
}
public static synchronized void addOnlineCount() {
WebSocketTest.onlineCount++;
}
public static synchronized void subOnlineCount() {
WebSocketTest.onlineCount--;
}
}
html代碼
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta content="text/html;charset=UTF-8"/>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
</head>
<body>
webSocket初見<br/>
<input id="text" type="text"/>
<button onclick="send()">發(fā)送消息</button>
<hr/>
<button onclick="closeWebSocket()">關(guān)閉WebSocket連接</button>
<hr/>
<div id="message"></div>
<script type="text/javascript">
var websocket = null;
//判斷當(dāng)前瀏覽器是否支持WebSocket
if ('WebSocket' in window) {
websocket = new WebSocket("ws://localhost:9001/wesocket/mywebsocket");
}
else {
alert('當(dāng)前瀏覽器 Not support websocket')
}
//連接發(fā)生錯誤的回調(diào)方法
websocket.onerror = function () {
setMessageInnerHTML("WebSocket連接發(fā)生錯誤");
};
//連接成功建立的回調(diào)方法
websocket.onopen = function () {
setMessageInnerHTML("WebSocket連接成功");
}
//接收到消息的回調(diào)方法
websocket.onmessage = function (event) {
setMessageInnerHTML(event.data);
}
//連接關(guān)閉的回調(diào)方法
websocket.onclose = function () {
setMessageInnerHTML("WebSocket連接關(guān)閉");
}
//監(jiān)聽窗口關(guān)閉事件躯肌,當(dāng)窗口關(guān)閉時,主動去關(guān)閉websocket連接破衔,防止連接還沒斷開就關(guān)閉窗口清女,server端會拋異常。
window.onbeforeunload = function () {
closeWebSocket();
}
//將消息顯示在網(wǎng)頁上
function setMessageInnerHTML(innerHTML) {
document.getElementById('message').innerHTML += innerHTML + '<br/>';
}
//關(guān)閉WebSocket連接
function closeWebSocket() {
websocket.close();
}
//發(fā)送消息
function send() {
var message = document.getElementById('text').value;
websocket.send(message);
}
</script>
</body>
</html>