后台代码
package com.xiaoc.websocket.servlet;
import java.io.IOException;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.concurrent.atomic.AtomicInteger;
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import org.apache.juli.logging.Log;
import org.apache.juli.logging.LogFactory;
@ServerEndpoint(value = "/websocket/chat")
public class webSocketDemoServlet {
private static final Log log = LogFactory.getLog(webSocketDemoServlet.class);
private static final String GUEST_PREFIX = "Guest";
private static final AtomicInteger connectionIds = new AtomicInteger(0);
private static final Set<webSocketDemoServlet> connections = new CopyOnWriteArraySet<webSocketDemoServlet>();
private String nickname;
private Session session;
public webSocketDemoServlet() {
nickname = GUEST_PREFIX + connectionIds.getAndIncrement();
}
@OnOpen
public void start(Session session) {
this.session = session;
connections.add(this);
String message = String.format("* %s %s", nickname, "has joined.");
broadcast(message);
}
@OnClose
public void end() {
connections.remove(this);
String message = String.format("* %s %s", nickname, "has disconnected.");
broadcast(message);
}
@OnMessage
public void incoming(String message) {
System.out.println(message);
broadcast(message);
}
@OnError
public void onError(Throwable t) throws Throwable {
log.error("Chat Error: " + t.toString(), t);
}
private static void broadcast(String msg) {
for (webSocketDemoServlet client : connections) {
try {
synchronized (client) {
client.session.getBasicRemote().sendText(msg);
}
} catch (IOException e) {
log.debug("Chat Error: Failed to send message to client", e);
connections.remove(client);
try {
client.session.close();
} catch (IOException e1) {
}
String message = String.format("* %s %s", client.nickname, "has been disconnected.");
broadcast(message);
}
}
}
}
前端页面
<!DOCTYPE HTML>
<html>
<head>
<title>WebSocket demo</title>
<style>
body {
padding: 40px;
}
#outputPanel {
margin: 10px;
padding: 10px;
background: #eee;
border: 1px solid #000;
min-height: 300px;
}
</style>
</head>
<body>
<input type="text" id="messagebox" size="60" />
<input type="button" id="buttonSend" value="Send Message" />
<input type="button" id="buttonConnect" value="Connect to server" />
<input type="button" id="buttonClose" value="Disconnect" />
<br>
<%
out.println("Session ID = " + session.getId());
%>
<div id="outputPanel"></div>
</body>
<script type="text/javascript">
var infoPanel = document.getElementById('outputPanel');
var textBox = document.getElementById('messagebox');
var sendButton = document.getElementById('buttonSend');
var connButton = document.getElementById('buttonConnect');
var discButton = document.getElementById('buttonClose');
var console = {
log : function(text) {
infoPanel.innerHTML += text + "<br>";
}
};
var demo = {
socket : null,
host : '',
connect : function() {
window.WebSocket = window.WebSocket || window.MozWebSocket;
if (!window.WebSocket) {
console.log('Error: WebSocket is not supported .');
return;
}
this.socket = new WebSocket(this.host);
this.socket.onopen = function() {
console.log("websocket is opened .");
};
this.socket.onmessage = function(message) {
console.log(message.data);
};
this.socket.onclose = function() {
console.log("websocket is closed .");
demo.socket = null;
};
},
send : function(message) {
if (this.socket) {
this.socket.send(message);
return true;
}
console.log('please connect to the server first !!!');
return false;
}
};
demo.host = (window.location.protocol == 'http:') ? 'ws://' : 'wss://';
demo.host += window.location.host + '/websocket/chat';
sendButton.onclick = function() {
var message = textBox.value;
if (!message)
return;
if (!demo.send(message))
return;
textBox.value = '';
};
connButton.onclick = function() {
if (!demo.socket)
demo.connect();
else
console.log('websocket already exists .');
};
discButton.onclick = function() {
if (demo.socket)
demo.socket.close();
else
console.log('websocket is not found .');
};
</script>
</html>