啥是websocket?
websocket是一種基於TCP協議的一種新的協議,和HTTP是並存的兩者不同協議。
既然是協議,就必然像HTTP那樣涉及到客戶端和服務端。
目前客戶端的實現比較統一,各個瀏覽器廠商都是遵循的W3C的H5技術來支持websocket的。
但是服務端的實現在技術提出初期,由於沒有一套統一的Java API標準,各個服務器中間件(tomcat、jetty)的實現各不相同;
直到Oracle發佈了基於JDK7的JSR356規範,使WebSocket的Java API得到了統一。所以只要Web容器支持JSR356,那麼我們寫WebSocket時,代碼就都是一樣的了。
Tomcat從7.0.81開始支持JSR356,但是tomcat7.X對websocket的實現,不如tomcat8.X的實現用着方便。tomcat8開發了好多標籤,開發起來方便多了。jetty從9.3開始支持websocket,具體見下圖:
websocket有啥作用?
(1)對於http協議,只能客戶端發起請求時,服務端才響應客戶端。也就是說,客戶端想要要什麼東西,都是客戶端主動去拿。實現不了服務端主動去給。
(2)對於websocket協議,服務端和客戶端的通信是雙向的,客戶端可以請求服務器從服務器拿數據,服務器數據更新了,也可以直接推送給客戶端。websocket協議相比HTTP協議,可以高效節能的通過雙向通信實現數據的實時傳輸。
如何使用?
開發環境要求:
JDK1.7及以上;
中間件支持JSR356規範;一般支持了JSR356規範的中間件就支持websocket;
框架的話,spring貌似4.X開始支持websocket;使用場景舉例:
消息廣播、在線多組討論、 個人消息推送代碼示例:
web工程下需要引入tomcat服務器裏lib文件夾下的websocket-api.jar
***********************消息廣播-客戶端************************
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<!DOCTYPE HTML>
<html>
<head>
<title>消息廣播</title>
</head>
<body>
<p>場景描述:消息廣播</p>
<input id="text" type="text"/>
<button onclick="send()">發送消息</button> <button onclick="closeWebSocket()">關閉WebSocket連接</button>
<hr/>
<div id="message"></div>
<hr/>
</body>
<script type="text/javascript">
var websocket = null;
//判斷當前瀏覽器是否支持WebSocket
if ('WebSocket' in window) {
websocket = new WebSocket("ws://localhost:9082/TestWebSocket/yuxingxing/websocket1");
}
else {
alert('當前瀏覽器 Not support websocket')
}
//連接發生錯誤的回調方法
websocket.onerror = function () {
setMessageInnerHTML("WebSocket連接發生錯誤");
};
//連接成功建立的回調方法
websocket.onopen = function () {
setMessageInnerHTML("WebSocket連接成功");
}
//接收到消息的回調方法
websocket.onmessage = function (event) {
setMessageInnerHTML(event.data);
}
//連接關閉的回調方法
websocket.onclose = function () {
setMessageInnerHTML("WebSocket連接關閉");
}
//監聽窗口關閉事件,當窗口關閉時,主動去關閉websocket連接,防止連接還沒斷開就關閉窗口,server端會拋異常。
window.onbeforeunload = function () {
closeWebSocket();
}
//將消息顯示在網頁上
function setMessageInnerHTML(innerHTML) {
document.getElementById('message').innerHTML += innerHTML + '<br/>';
}
//關閉WebSocket連接
function closeWebSocket() {
websocket.close();
}
//發送消息
function send() {
var message = document.getElementById('text').value;
websocket.send(message);
}
</script>
</html>
***********************消息廣播-服務端************************
package com.yuxingxing.server;
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;
/**
* @Description 場景:消息廣播
* @author yuxingxing
* @date 2017-6-14 上午10:38:20
*/
@ServerEndpoint(value = "/yuxingxing/websocket1")
public class MyServer {
// 靜態變量,用來記錄當前在線連接數。應該把它設計成線程安全的。
private static int onlineCount = 0;
// concurrent包的線程安全Set,用來存放每個客戶端對應的MyWebSocket對象。若要實現服務端與單一客戶端通信的話,可以使用Map來存放,其中Key可以爲用戶標識
private static CopyOnWriteArraySet<MyServer> webSocketSet = new CopyOnWriteArraySet<MyServer>();
// 與某個客戶端的連接會話,需要通過它來給客戶端發送數據
private Session session;
/**
* 連接建立成功調用的方法
*
* @param session
* 可選的參數。session爲與某個客戶端的連接會話,需要通過它來給客戶端發送數據
*/
@OnOpen
public void onOpen(Session session) {
this.session = session;
webSocketSet.add(this); // 加入set中
addOnlineCount(); // 在線數加1
System.out.println("有新連接加入!當前在線人數爲" + getOnlineCount());
}
/**
* 連接關閉調用的方法
*/
@OnClose
public void onClose() {
webSocketSet.remove(this); // 從set中刪除
subOnlineCount(); // 在線數減1
System.out.println("有一連接關閉!當前在線人數爲" + getOnlineCount());
}
/**
* 收到客戶端消息後調用的方法
*
* @param message
* 客戶端發送過來的消息
* @param session
* 可選的參數
*/
@OnMessage
public void onMessage(String message, Session session) {
System.out.println("來自客戶端的消息:" + message);
// 羣發消息
for (MyServer item : webSocketSet) {
try {
item.sendMessage(message);
} catch (IOException e) {
e.printStackTrace();
continue;
}
}
}
/**
* 發生錯誤時調用
*
* @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 synchronized int getOnlineCount() {
return onlineCount;
}
public static synchronized void addOnlineCount() {
MyServer.onlineCount++;
}
public static synchronized void subOnlineCount() {
MyServer.onlineCount--;
}
}
***********************在線討論組-客戶端************************
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<!DOCTYPE HTML>
<html>
<head>
<title>在線多組討論</title>
</head>
<body>
<p>場景描述:在線多組討論</p>
<input id="nickName" type="text" placeholder="請輸入您的聊天暱稱"/>
<button onclick="openWebsocket('平民')">進入【平民】討論組</button>
<button onclick="openWebsocket('狼人')">進入【狼人】討論組</button></BR></BR></BR>
<input id="text" type="text"/><button onclick="send()">發送消息</button> <button onclick="closeWebSocket()">退出當前討論組</button>
<hr/></BR></BR>
<div id="message"></div>
</body>
<script type="text/javascript">
var websocket = null;
var nickName = null;
function openWebsocket(selectedGroupName){
var name = document.getElementById('nickName').value;
if(name == ""){
alert("請輸入您的暱稱!");
return;
}
nickName = name;
document.getElementById('message').innerHTML = "";
//判斷當前瀏覽器是否支持WebSocket
if ('WebSocket' in window) {
websocket = new WebSocket("ws://localhost:9082/TestWebSocket/yuxingxing/websocket1/"+selectedGroupName+"/"+nickName);
}
else {
alert('當前瀏覽器 Not support websocket')
}
//連接發生錯誤的回調方法
websocket.onerror = function () {
setMessageInnerHTML("WebSocket連接發生錯誤");
};
//連接成功建立的回調方法
websocket.onopen = function () {
setMessageInnerHTML("您已進入討論組:"+selectedGroupName);
}
//接收到消息的回調方法
websocket.onmessage = function (event) {
setMessageInnerHTML(event.data);
}
//連接關閉的回調方法
websocket.onclose = function () {
setMessageInnerHTML("WebSocket連接關閉");
}
//監聽窗口關閉事件,當窗口關閉時,主動去關閉websocket連接,防止連接還沒斷開就關閉窗口,server端會拋異常。
window.onbeforeunload = function () {
closeWebSocket();
}
//將消息顯示在網頁上
function setMessageInnerHTML(innerHTML) {
document.getElementById('message').innerHTML += innerHTML + '<br/>';
}
//關閉WebSocket連接
function closeWebSocket() {
websocket.close();
}
}
//發送消息
function send() {
var message = document.getElementById('text').value;
websocket.send(message);
}
</script>
</html>
***********************在線討論組-服務端************************
package com.yuxingxing.server;
import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
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.PathParam;
import javax.websocket.server.ServerEndpoint;
/**
* @Description 場景:在線多個討論組
* @author yuxingxing
* @date 2017-6-28 上午10:36:44
*/
@ServerEndpoint(value = "/yuxingxing/websocket1/{groupName}/{nickName}")
public class MyServerGroup {
// 靜態變量,用來記錄當前在線連接數。應該把它設計成線程安全的。
private static int onlineCount = 0;
// concurrent包的線程安全Map,用來存放各個討論組集合。<key=討論組名稱,value=討論組人員名稱>
private static ConcurrentMap<String, CopyOnWriteArraySet<MyServerGroup>> webSocketGroupap = new ConcurrentHashMap<String, CopyOnWriteArraySet<MyServerGroup>>();
// 與某個客戶端的連接會話,需要通過它來給客戶端發送數據
private Session session;
// 討論組名稱
private String groupName;
// 用戶暱稱
private String nickName;
/**
* 客戶端與服務端建立鏈接
*
* @param session
* 通話session
* @param groupName
* 討論組名稱
* @param nickName
* 用戶暱稱
*/
@OnOpen
public void onOpen(Session session, @PathParam(value = "groupName") String groupName,
@PathParam(value = "nickName") String nickName) {
this.session = session;
this.groupName = groupName;
this.nickName = nickName;
// 將用戶加入相應的討論組
boolean needCreateGroup = (webSocketGroupap.get(groupName) == null);
if (needCreateGroup) {
CopyOnWriteArraySet<MyServerGroup> group = new CopyOnWriteArraySet<MyServerGroup>();
webSocketGroupap.put(groupName, group);
}
CopyOnWriteArraySet<MyServerGroup> groupOfUser = webSocketGroupap.get(groupName);
groupOfUser.add(this);
// 在線數加1
addOnlineCount();
System.out.println(nickName + "加入了討論組" + groupName + "!當前在線人數爲" + getOnlineCount());
}
/**
* 客戶端關閉連接事件
*
* @param groupName
* @param nickName
*/
@OnClose
public void onClose(@PathParam(value = "groupName") String groupName, @PathParam(value = "nickName") String nickName) {
CopyOnWriteArraySet<MyServerGroup> groupOfUser = webSocketGroupap.get(groupName);
groupOfUser.remove(this);
subOnlineCount(); // 在線數減1
System.out.println(nickName + "退出了討論組" + groupName + "!當前在線人數爲" + getOnlineCount());
// 討論組沒人時,移除該討論組
if (groupOfUser.size() == 0) {
System.out.println("討論組【" + groupName + "】被移除");
webSocketGroupap.remove(groupName);
}
}
/**
* 發生錯誤時調用
*
* @param session
* @param error
*/
@OnError
public void onError(Session session, Throwable error, @PathParam(value = "groupName") String groupName) {
System.out.println("討論組【" + groupName + "】發生錯誤");
error.printStackTrace();
}
@OnMessage
public void onMessage(String message, Session session, @PathParam(value = "groupName") String groupName,
@PathParam(value = "nickName") String nickName) {
System.out.println("來自討論組【" + groupName + "】的" + nickName + "說話了;" + message);
// 針對當前討論組,羣發消息
CopyOnWriteArraySet<MyServerGroup> groupOfUser = webSocketGroupap.get(groupName);
for (MyServerGroup item : groupOfUser) {
try {
item.sendMessage(nickName + ":" + message);
} catch (IOException e) {
System.out.println("發送消息失敗!");
e.printStackTrace();
continue;
}
}
}
/**
* 這個方法與上面幾個方法不一樣。沒有用註解,是根據自己需要添加的方法。
*
* @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() {
MyServerGroup.onlineCount++;
}
public static synchronized void subOnlineCount() {
MyServerGroup.onlineCount--;
}
}
@ServerEndpoint註解的configurator屬性,可以自定義配置信息。客戶端和服務端握手階段,會先執行自定義的配置信息類,然後再執行open方法。
首先,自定義一個配置類:
package com.yuxingxing.configurator;
import java.util.Map;
import javax.websocket.HandshakeResponse;
import javax.websocket.server.HandshakeRequest;
import javax.websocket.server.ServerEndpointConfig;
import javax.websocket.server.ServerEndpointConfig.Configurator;
/**
* @Description 服務端配置類,對所有客戶端生效
* @author yuxingxing
* @date 2017-6-30 下午2:23:46
*/
public class MyConfigurator extends Configurator {
@Override
public void modifyHandshake(ServerEndpointConfig sec, HandshakeRequest request, HandshakeResponse response) {
// TODO Auto-generated method stub
Map<String, Object> configMap = sec.getUserProperties();
configMap = sec.getUserProperties();
configMap.put("config1", "config1-value");
configMap.put("config2", "config2-value");
}
}
然後給服務端的註解配置這個類,在服務端的各個方法裏就可以獲取配置值了:
@ServerEndpoint(value = "/yuxingxing/websocket1", configurator = MyConfigurator.class)
public class MyServer {
//服務端代碼.........
this.session.getUserProperties().get("config1");
//服務端代碼.........
}
小結
以下內容是在學習tomcat8的websocket過程中的一些知識點和注意事項,記錄下來,方便日後回顧和理解。
(1)對於tomcat有三種連接器:bio連接器(默認)、nio連接器、apr連接器。雖然 WebSocket 可以和任何 HTTP 連接器一起使用,但並不建議和 bio連接器一起使用。因爲 WebSocket 典型用途下,大量連接很多時候都是空閒的,而bio連接器不管連接是否空閒,每個連接都會分配一個線程。這就會導致tomcat服務器會產生大量的空閒線程,從而佔用內存,浪費資源。
tomcat官網:目前,已有報告(56304)發現,Linux 會用大量時間來報告刪除的連接。當利用 BIO HTTP 連接器使用 WebSocket 時,當在這段時間內寫入時,就容易產生線程阻塞。建議選擇nio 連接器,因爲它使用的是非阻塞 IO,從而能解決這些問題。
優秀文章鏈接:
http://blog.csdn.net/frank_good/article/details/50856585
https://www.ibm.com/developerworks/cn/java/j-lo-WebSocket/