转载请保留作者信息:
作者:88250
时间:2010 年 1 月 1 日
我们通过一个简单的例子来熟悉 HTML 5 WebSocket。该例子服务端从 0 开始每秒递增一个整数并发送给客户端浏览器显示。准备:下载 Jetty 7
,Java Web 开发环境,Chrome 4+
。
服务端 Java 代码:
final public class CounterSocketServlet extends WebSocketServlet {
@Override
protected WebSocket doWebSocketConnect(final HttpServletRequest hsr,
final String string) {
return new CounterSocket();
}
final class CounterSocket implements WebSocket {
private Outbound outbound;
public void onConnect(final Outbound outbound) {
System.out.println("onConnect");
this.outbound = outbound;
}
public void onMessage(final byte frame, final String data) {
System.out.println("onMessage");
if (data.equals("Hello, Server!")) {
new Thread() {
@Override
public void run() {
try {
outbound.sendMessage(frame, "Hello, browser :-)");
int i = 0;
while (true) {
sleep(1000);
outbound.sendMessage(frame, String.valueOf(i++));
}
} catch (final Exception e) {
System.err.println(e.getMessage());
}
}
}.start();
}
}
public void onMessage(final byte frame, final byte[] data,
final int offset, final int length) {
throw new UnsupportedOperationException("Not supported yet.");
}
public void onDisconnect() {
System.out.println("onDisconnect");
}
}
}
浏览器客户端 HTML 代码:
<html>
<head>
<title>WebSoket Demo</title>
<script type="text/javascript">
if (!window.WebSocket) {
alert("WebSocket not supported by this browser!");
}
function display() {
var valueLabel = document.getElementById("valueLabel");
valueLabel.innerHTML = "";
var ws = new WebSocket(
"ws://localhost:8080/WebSocketDemo/counter-socket");
ws.onmessage = function(evt) {
valueLabel.innerHTML = evt.data;
};
ws.onclose = function() {
};
ws.onopen = function() {
ws.send("Hello, Server!");
};
}
</script>
</head>
<body onload="display();">
<div id="valueLabel"></div>
</body>
</html>
运行:
- 部署
将打包好的 WebSocketDemo.war 复制到 Jetty 安装目录:
- 启动 Jetty
C:\jetty-distribution-7.0.1.v20091125>java -jar start.jar - 测试
进一步阅读:
资源: