WebScocket Example
转载自:http://blog.sina.com.cn/s/blog_a8b026160101jqnq.html
分类: JSP |
<!-- 正文开始 -->
1.客户端:
var ws = null;
function setConnected(connected) { // 按钮状态转换
document.getElementByIdx_x('connect').disabled = connected;
document.getElementByIdx_x('disconnect').disabled = !connected;
document.getElementByIdx_x('echo').disabled = !connected;
}
function connect() { // 链接方式及对象
var target = document.getElementByIdx_x('target').value;
if (target == '') {
alert('Please select server side connection implementation.');
return;
}
if ('WebSocket' in window) {
ws = new WebSocket(target);
} else if ('MozWebSocket' in window) {
ws = new MozWebSocket(target);
} else {
alert('WebSocket is not supported by this browser.');
return;
}
ws.onopen = function () { // 链接成功处理
setConnected(true);
log('Info: WebSocket connection opened.');
};
ws.onmessage = function (event) { // 收到服务器信息
log('Received: ' + event.data);
};
ws.onclose = function () { // 链接中断处理
setConnected(false);
log('Info: WebSocket connection closed.');
};
}
function disconnect() { // 按钮中断链接
if (ws != null) {
ws.close();
ws = null;
}
setConnected(false);
}
function echo() { // 信息发送
if (ws != null) {
var message = document.getElementByIdx_x('message').value;
log('Sent: ' + message);
ws.send(message);
} else {
alert('WebSocket connection not established, please connect.');
}
}
function updateTarget(target) { // 链接方式及对象
if (window.location.protocol == 'http:') {
document.getElementByIdx_x('target').value = 'ws://' + window.location.host + target;
} else {
document.getElementByIdx_x('target').value = 'wss://' + window.location.host + target;
}
}
function log(message) { // 客户端显示
var console = document.getElementByIdx_x('console');
var p = document.createElement_x('p');
p.style.wordWrap = 'break-word';
p.appendChild(document.createTextNode(message));
console.appendChild(p);
while (console.childNodes.length > 25) {
console.removeChild(console.firstChild);
}
console.scrollTop = console.scrollHeight;
}
document.addEventListener("DOMContentLoaded", function() {
// Remove elements with "noscript" class -<noscript></noscript>
var noscripts = document.getElementsByClassName("noscript");
for (var i = 0; i < noscripts.length; i++) {
noscripts[i].parentNode.removeChild(noscripts[i]);
}
}, false);
页面设计:
onclick="updateTarget(this.value);"/>
onclick="updateTarget(this.value);"/> annotation
Connect
Disconnect
Echo message
2. 服务器端
package websocket.echo;
import java.io.IOException;
import java.nio.ByteBuffer;
import javax.websocket.OnMessage;
import javax.websocket.PongMessage;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
@ServerEndpoint("/websocket/testecho") // 指定程序位置
public class testecho {
@OnMessage // 收到字符串信息
public void echoTextMessage(Session session, String msg, boolean last) { // 收到客户端字符串
try {
if (session.isOpen()) {
System.out.println("session的值是: "+session.toString());
System.out.println("testecho 发送字符串消息"+msg);
msg=msg+"testecho返回";
session.getBasicRemote().sendText(msg, last); // 发回客户端
msg="123456";
session.getBasicRemote().sendText(msg, last);
}
} catch (IOException e) {
try {
session.close();
} catch (IOException e1) { }
}
}
@OnMessage // 收到二进制信息
public void echoBinaryMessage(Session session, ByteBuffer bb,boolean last){ // 收到客户端二进制
try {
if (session.isOpen()) {
System.out.println("testecho 发送二进制消息"+bb);
session.getBasicRemote().sendBinary(bb, last); // 发回客户端
}
} catch (IOException e) {
try {
session.close();
} catch (IOException e1) { }
}
}
@OnMessage
public void echoPongMessage(PongMessage pm) {
// NO-OP
}
}