JavaEE 7教程

WebSocket客户端

上页

你可以用@clientendpoint标注一个POJO作为WebSocket客户端点:


@ClientEndpoint
public class MyClientEndpoint {
//. . .
}

您可以通过指定截获的生命周期事件”,@OnClose,和@OnError 注释方法:
@ClientEndpoint
public class MyClientEndpoint {
@OnOpen
public void open(Session s) {
//. . .
}
@OnClose
public void close(CloseReason c) {
//. . .
}
@OnError
public void error(Throwable t) {
//. . .
}
}

在开放的方法使用session:
@OnOpen
public void onOpen(Session session) {
try {
session.getBasicRemote().sendText("Duke");
} catch (IOException ex) {
//. . .
}
}

消息接受是任何Java方法需要标注 @ onMessage:
@OnMessage
public void processMessage(String message, Session session) {
//. . .
}

客户可以通过containerprovider连接端点:
WebSocketContainer container = ContainerProvider.getWebSocketContainer();
String uri = "ws://localhost:8080/myApp/websocket";
container.connectToServer(MyClient.class, URI.create(uri));



客户端的JavaScript WebSocket

   你可以使用定义的JavaScript API 调用一个WebSocket端点。 指定URL和一个可选的连接到一个WebSocket端点 :
var websocket = new WebSocket("ws://localhost:8080/myapp/chat");

该API还定义了不同的生命周期方法调用事件处理程序:
OnOpen一个新的连接启动时被调用,。
onerror收到错误消息时被调用。
OnClose连接终止时被调用:

websocket.onopen = function() {
//. . .
}
websocket.onerror = function(evt) {
//. . .
}
websocket.onclose = function() {
//. . .
}

文本或二进制数据都可以发送:
websocket.send(myField.value);

websocket.binaryType = "arraybuffer";
var buffer = new ArrayBuffer(myField.value);
var bytes = new Uint8Array(buffer);
for (var i=0; i<bytes.length; i++) {
    bytes[i] = i;
}
websocket.send(buffer);

 

消息可以通过onmessage事件句柄接收:
websocket.onmessage = function(evt) {
  console.log("message received: " + evt.data);
}

与Java EE安全集成

   WebSocket 端点建立是基于servlet定义的身份验证和授权安全机制。 一个WebSocket试图启动一个连接时必须先前认证 。通常情况下,这是 通过HTTP验证执行(也许是基本或基于表单的Web应用程序) 。

你可以通过web.xml部署描述符建立基本的认证:
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
version="3.1">
<security-constraint>
 <web-resource-collection>
  <web-resource-name>WebSocket Endpoint</web-resource-name>
  <url-pattern>/*</url-pattern>
  <http-method>GET</http-method>
 </web-resource-collection>
<auth-constraint>
 <role-name>g1</role-name>
</auth-constraint>
</security-constraint>
<login-config>
 <auth-method>BASIC</auth-method>
 <realm-name>file</realm-name>
</login-config>
<security-role>
<role-name>g1</role-name>
</security-role>
</web-app>