WebSocket API簡介:
首先看一段簡單的javascript代碼,該代碼調用了WebSockets的API。
- var ws = new WebSocket(“ws://echo.websocket.org”);
- ws.onopen = function(){ws.send(“Test!”); };
- ws.onmessage = function(evt){console.log(evt.data);ws.close();};
- ws.onclose = function(evt){console.log(“WebSocketClosed!”);};
- ws.onerror = function(evt){console.log(“WebSocketError!”);};
這份代碼總共只有5行,現在簡單概述一下這5行代碼的意義。
第一行代碼是在申請一個WebSocket對象,參數是需要連接的服務器端的地址,同http協議使用http://開頭一樣,WebSocket協議的URL使用ws://開頭,另外安全的WebSocket協議使用wss://開頭。
第二行到第五行爲WebSocket對象註冊消息的處理函數,WebSocket對象一共支持四個消息 onopen, onmessage, onclose和onerror,當Browser和WebSocketServer連接成功後,會觸發onopen消息;如果連接失敗,發送、接收數據失敗或者處理數據出現錯誤,browser會觸發onerror消息;當Browser接收到WebSocketServer發送過來的數據時,就會觸發onmessage消息,參數evt中包含server傳輸過來的數據;當Browser接收到WebSocketServer端發送的關閉連接請求時,就會觸發onclose消息。我們可以看出所有的操作都是採用消息的方式觸發的,這樣就不會阻塞UI,使得UI有更快的響應時間,得到更好的用戶體驗。
實現:
@ServerEndpoint(value = "/websocket/{random}")
public class WebSocket {
private static final Set<WebSocket> connections =
new CopyOnWriteArraySet<WebSocket>();
private Session session;
private String random;
public WebSocket() {
}
/*當websocket的客戶端連接到服務器時候,這個方法就會執行,並且傳遞一個session會話對象來
我們拿到這話session,就是可以給客戶端發送消息*/
@OnOpen
public void start(Session session,@PathParam("random") String random) {
this.random=random;
System.out.println(random);
this.session = session;
connections.add(this);
}
/*客戶端被關閉時候,就會自動會調用這個方法*/
@OnClose
public void end() {
connections.remove(this);
}
/*客戶端給服務器發送消息,這個方法會自動調用,並且可以拿到發送過來的數據*/
@OnMessage
public void incoming(String message) {
// Never trust the client
//sendByIp("10.104.5.51","only to the first");
System.out.println(random+":"+message);
broadcast(message);
}
/*發生了異常自動執行*/
@OnError
public void onError(Throwable t) throws Throwable {
}
/*廣播:遍歷客戶端集,發送消息,注意發送要用的session,用session.getBasicRemote().sendText(msg)發送消息*/
public static void broadcast(String msg) {
for (WebSocket client : connections) {//遍歷所有
try {//如果這個client已經在線
synchronized (client) {
client.session.getBasicRemote().sendText(msg);//發送消息
}
} catch (IOException e) {//如果這個client不在線
connections.remove(client);
try {
client.session.close();
} catch (IOException e1) {
// Ignore
}
}
}
}
}