WbSocket官方协议内容: http://datatracker.ietf.org/doc/rfc6455/?include_text=1
连接请求内容:
服务端接收请求后主要是成针对Sec-WebSocket-Key生成对就Sec-WebSocket-Accept 的key,生成Sec-WebSocket-Accept值比较简单就是Sha1(Sec-WebSocket-Key+258EAFA5-E914-47DA-95CA-C5AB0DC85B11)即可
在Tomcat8中集成了websocket-api.jar.他对WebSocket协议进行的封装:
package com.lgy.websocket;
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;
@ServerEndpoint(value = "/websocket/chat")
public class HelloWebSocketServlet {
//private static final Log log = LogFactory.getLog(ChatAnnotation.class);
private static final String GUEST_PREFIX = "Guest";
private static final AtomicInteger connectionIds = new AtomicInteger(0);
private static final Set connections = new CopyOnWriteArraySet<>();
private final String nickname;
private Session session;
public HelloWebSocketServlet() {
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.");
System.out.println(message);
}
//接受消息
@OnMessage
public void incoming(String message) {
System.out.println(message.toString());
//broadcast(filteredMessage);
broadcast(message.toString());
}
//客户端关闭了连接
@OnClose
public void end() {
connections.remove(this);
String message = String.format("* %s %s", nickname, "has disconnected.");
System.out.println(message);
//broadcast(message);
}
//WebSocket服务出错
@OnError
public void onError(Throwable t) throws Throwable {
//log.error("Chat Error: " + t.toString(), t);
}
private static void broadcast(String msg) {
for (HelloWebSocketServlet 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) {
// Ignore
}
String message = String.format("* %s %s",
client.nickname, "has been disconnected.");
broadcast(message);
}
}
}
}