websocket-getAsyncRemote() Versus getBasicRemote()

websocket-getAsyncRemote() Versus getBasicRemote()

WebSocket是一種網路傳輸協定,可在單個TCP連接上進行全雙工通訊,位於OSI模型的應用層。
WebSocket協定在2011年由IETF標準化為RFC 6455,後由RFC 7936補充規範。Web IDL中的WebSocket API由W3C標準化。

WebSocket使得客戶端和伺服器之間的資料交換變得更加簡單,允許伺服器端主動向客戶端推播資料。
在WebSocket API中,瀏覽器和伺服器只需要完成一次交握,兩者之間就可以建立永續性的連接,並進行雙向資料傳輸。

websocket Session sendText() 有兩種模式

1
2
3
4
5
6
7
8
(1) session.getAsyncRemote().sendText()
非同步
可平行處理,一次發送多個
不在乎順序

(2) session.getBasicRemote().sendText()
同步
第二個要等第一個發送完才繼續發送

session.getBasicRemote().sendText()

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
/**
* Send a text message in parts, blocking until all of the message has been transmitted. The runtime
* reads the message in order. Non-final parts of the message are sent with isLast set to false. The final part
* must be sent with isLast set to true.
*
* @param partialMessage the parts of the message being sent.
* @param isLast Whether the partial message being sent is the last part of the message.
* @throws IOException if there is a problem delivering the message fragment.
* @throws IllegalArgumentException if the partialMessage is {@code null}.
*/
void sendText(String partialMessage, boolean isLast) throws IOException;

exmaple:
session.getBasicRemote().sendText(message, false); 
session.getBasicRemote().sendBinary(data);
session.getBasicRemote().sendText(message, true); 

由於同步特性,第二行必须等待第一行發送完成後才能進行,而第一行的剩餘message要等第二行
發送完才能繼續發送,所以在第二行會throw IllegalStateException。
如果要使用getBasicRemote()同步sendText,請避免一次發送全部,使用部分發送。

結論

1
2
大部分的情況請使用非同步session.getAsyncRemote().sendText()方法
有特殊需求要進行部分發送時,請使用session.getBasicRemote().sendText()方法