先日に続きOracleのサイトをみながらぼちぼち試していきます。
@OnMessageの戻り値
If the return type of the method annotated with @OnMessage
is not void
, the WebSocket implementation will send the return value to the other peer.
戻り値付のメソッドの場合、その値をpeerに返すというような事が書いてあるので試してみる。
(ソース)
@OnMessage
public String onMessage(String message) {
System.out.println(“message[” + message + “]”);
return message;
}
実際にメッセージを送ったブラウザには戻り値が帰ってきたことを確認できた。
ただし、開いていた他のブラウザには送信されていない。
peerと書いているだけなので複数に返すのでなく単独のものに返すという動作という認識であっているのかな??
疑問は残るけど、複数ブラウザ(peer)に返すサンプルがあるgetAsyncRemote
、getBasicRemote()
を試してみる。APIによると非同期か同期かの違いらしい。
@OnMessageのgetAsyncRemote/getBasicRemote
ソースを書き換えてみたけれども、
とgetAsyncRemote
の両方とも同時にalert(“Calling”);まで進む。getBasicRemote
RemoteEndpoint.Basic
をみると下のように書かれているのでのでJSのAlert文で待ちが入るというわけではないらしい。
The point of completion of the send is defined when all the supplied data has been written to the underlying connection
送信失敗に備えたエラー処理をするためのもので、Endpoint間の同期をとる目的でないということでよいのかな。
(java)
static Set<Session> sessions = Collections
.synchronizedSet(new HashSet<Session>());
@OnMessage
public void onMessage(String message) {
System.out.println(“message[” + message + “]”);
for (Session s : sessions) {
s.getAsyncRemote().sendText(message);
}
}
@OnMessage
public void onMessage(String message) throws IOException {
System.out.println(“message[” + message + “]”);
for (Session s : sessions) {
s.getBasicRemote().sendText(message);
}
}
(JS)
socket.onmessage = function(message){
alert(“Calling”);
$(‘#log’).append(message.data + “<br/>”);
}