Java Reference
In-Depth Information
meters that can be taken, please see the specification). Messages can be sent syn-
chronously with the method
Session.getBasicRemote()
or asynchronously with
themethod
Session.getAsyncRemote()
.Eachofthesemethods isusedtosend
messages of type:
text
,
binary
,
object
,
ping
, and pong frames. The following
code demonstrates how to send a text message to all connected clients:
static Set<Session> users =
Collections.synchronizedSet(new HashSet());
@OnOpen
public void openConnection(Session session)
throws Exception {
users.add(session);
}
@OnMessage
public void onMessage(Session session, String
msg)throws Exception {
for (Session s : users) {
s.getBasicRemote().sendText(msg);
}
}
The session object contains a variable to store some user-specific information. The
code that follows demonstrates how to communicate with many customers by giving
the name of the person who sent the message each time:
//...
static Set<String> usersId =
Collections.synchronizedSet(new HashSet());
//...
@OnMessage
public void onMessage(Session session, String
msg)throws Exception {
if (msg.startsWith("ID")) {//if it is a
connection message