Tomcat实现WebSocket协议
JavaEE 7中出了JSR-356:Java API for WebSocket规范。不少Web容器,如Tomcat,Nginx,Jetty等都支持WebSocket。Tomcat从7.0.27开始支持 WebSocket,从7.0.47开始支持JSR-356,下面的Demo代码也是需要部署在Tomcat7.0.47以上的版本才能运行。
第一步、首先加入依赖jar包如下:
javaxjavaee-api7.0provided
注:因为tomcat已经包含websocket实现,所以这里scope设置为provided
第二步、使用@ServerEndpoint注解,创建一个websocket服务端cn.kunming.iss.core.websocketcom.jfinal.kit.LogKitcom.jfinal.kit.StrKitjavax.websocket.*javax.websocket.server.javax.websocket.server.java.io.IOException()
WebSocket {
= Session String (() String tokenSession session) Exception {
(StrKit.(token)){
LogKit.()}
LogKit.(+token).= token.= sessionWebSocketPool.(token)()LogKit.(+ ())}
(){
WebSocketPool.()()LogKit.(+ ())}
(String messageSession session) {
(.equals(message)){
{
sendMsg()} (IOException e) {
e.printStackTrace()}
}
LogKit.(+ message)}
(Session sessionThrowable error){
LogKit.(+error.getMessage())error.printStackTrace()}
(String message) IOException{
..getBasicRemote().sendText(message)}
() {
}
() {
WebSocket.++}
() {
WebSocket.--}
}
为了方便管理连接,再创建一个链接池:cn.kunming.iss.core.websocketjava.io.IOExceptionjava.util.Collectionjava.util.Mapjava.util.concurrent.ConcurrentHashMapWebSocketPool {
Map = ConcurrentHashMap<>()(String tokenWebSocket conn) {
.put(tokenconn)}
(String token) {
(.containsKey(token)) {
.remove(token)} {
}
}
WebSocket (String token) {
.get(token)}
(String tokenString msg) Exception {
(!= token && != .get(token)) {
.get(token).sendMsg(msg)}
}
(String msg){
Collection list = .values()(list) {
(WebSocket conn : list) {
(conn != ) {
{
conn.sendMsg(msg)} (IOException e) {
e.printStackTrace()}
}
}
}
}
}
第三步、HTML页面实现一个客户端
Java后端WebSocket的Tomcat实现Welcome()发送消息()关闭WebSocket连接websocket = (in ) {
websocket = WebSocket()}
{
()
}
websocket.= () {
()}websocket.= () {
()}
websocket.= (event) {
(event.)}
websocket.= () {
()}
.= () {
()}
(innerHTML) {
.().+= innerHTML + }
() {
websocket.()}
() {
message = .().websocket.(message)}