webSocket推送是常用于生产项目的模块,在我们部门做的一个汇报演示的demo中遇到了webSocket的一些问题。
自己下来看看了看webSocket的东西,结合spring boot 做了一个简单的demo;
介绍的部分大家可以参考众多的帖子,度娘
http://www.cnblogs.com/wei2yi/archive/2011/03/23/1992830.html
http://my.oschina.net/ldl123292/blog/304360
好的,现在贴一下我的代码 注释写的很细,也很简单,一下就能看懂。
java:
package com.haungteng.springboot.controller.websocket;
import org.springframework.stereotype.Component;
import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.CopyOnWriteArraySet;
/**
* @author ht
* @describle 统计在线人数的demo
*/
@Component
@ServerEndpoint("/websocket") //该注解表示该类被声明为一个webSocket终端
public class MySocket {
//初始在线人数
private static int online_num = 0;
//线程安全的socket集合
private static CopyOnWriteArraySet<MySocket> webSocketSet = new CopyOnWriteArraySet<MySocket>();
//会话
private Session session;
@OnOpen
public void onOpen(Session session){
this.session = session;
webSocketSet.add(this);
addOnlineCount();
System.out.println("有链接加入,当前人数为:"+getOnline_num());
}
@OnClose
public void onClose(){
webSocketSet.remove(this);
subOnlineCount();
System.out.println("有链接关闭,当前人数为:"+getOnline_num());
}
@OnMessage
public void onMessage(String message,Session session) throws IOException{
System.out.println("来自客户端的消息:"+message);
for(MySocket item:webSocketSet){
this.session.getAsyncRemote().sendText("hello");
}
}
public synchronized int getOnline_num(){
return MySocket.online_num;
}
public synchronized int subOnlineCount(){
return MySocket.online_num--;
}
public synchronized int addOnlineCount(){
return MySocket.online_num++;
}
}
html:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>My WebSocket</title> </head> <body> <h2 οnclick="openTanTan()" style="color:dodgerblue;text-align: center">WeTanTan</h2> <div id="tantanbox" style="width:800px;height:498