概念
在WebSocket概念出来之前,如果页面要不停地显示最新的价格,那么必须不停地刷新页面,或者用一段js代码每隔几秒钟发消息询问服务器数据。
而使用WebSocket技术之后,当服务器有了新的数据,会主动通知浏览器。
优点
1. 节约带宽。 不停地轮询服务端数据这种方式,使用的是http协议,head信息很大,有效数据占比低, 而使用WebSocket方式,头信息很小,有效数据占比高。
2. 无浪费。 轮询方式有可能轮询10次,才碰到服务端数据更新,那么前9次都白轮询了,因为没有拿到变化的数据。 而WebSocket是由服务器主动回发,来的都是新数据。
3. 实时性,考虑到服务器压力,使用轮询方式不可能很短的时间间隔,否则服务器压力太多,所以轮询时间间隔都比较长,好几秒,设置十几秒。 而WebSocket是由服务器主动推送过来,实时性是最高的
服务器端代码:每创建一个浏览器会话就创建一个WebServer对象。
OnOpen 表示有浏览器链接过来的时候被调用
OnClose 表示浏览器发出关闭请求的时候被调用
OnMessage 表示浏览器发消息的时候被调用
OnError 表示有错误发生,比如网络断开了等等
sendMessage 用于向浏览器回发消息
/**
* @ServerEndpoint 注解是一个类层次的注解,它的功能主要是将目前的类定义成一个websocket服务器端,
* 注解的值将被用于监听用户连接的终端访问URL地址,客户端可以通过这个URL来连接到WebSocket服务器端
*/
@ServerEndpoint("/server")
public class WebServer { //服务端
//与某个客户端的连接会话,需要通过它来给客户端发送数据
private Session session;
@OnOpen
public void onOpen(Session session){
this.session = session;
WebManger.add(this);
}
public void sendMessage(String message) throws IOException{
this.session.getBasicRemote().sendText(message); //同步方法
}
@OnClose
public void onClose(){
WebManger.remove(this);
}
@OnMessage
public void onMessage(String message, Session session) {
System.out.println("来自客户端的消息:" + message);
}
@OnError
public void onError(Session session, Throwable error){
System.out.println("发生错误");
error.printStackTrace();
}
}
再来一个负责管理每个浏览器会话(WebServer对象)的管理代码:
//ServerManager 中维护了一个线程安全的集合servers, 用于因为浏览器发起连接请求而创建的Server.
public class WebManger {
public static List<WebServer> list=Collections.synchronizedList(new ArrayList<WebServer>());
public static void broadCast(String message){
for(WebServer ws:list){
try {
ws.sendMessage(message);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public static int getTotal(){
return list.size();
}
public static void add(WebServer server){
list.add(server);
System.out.println("有新连接加入! 当前总连接数是:"+ list.size());
}
public static void remove(WebServer server){
list.remove(server);
System.out.println("有连接退出! 当前总连接数是:"+ list.size());
}
}
最后再来一个次线程,让他不停的刷新数据,来达到服务器主动给浏览器发送数据的目的。
//loadOnStartup标记为Servlet不是为了其被访问,而是为了便于伴随Tomcat一起启动
@WebServlet(urlPatterns ="/MyThread",loadOnStartup=1)
public class MyThread extends HttpServlet implements Runnable{
public void init(ServletConfig config){
new Thread(this).start();
}
@Override
public void run() {
int price=1000;
int count=1;
while (true) {
try {
Thread.sleep(2000);
float random = 1+(float) (Math.random()-0.5);
count=WebManger.getTotal();
if (count==0) {
count=1;
}
//随着人数改变价格
price=(int)(random*price*count);
//格式化字符串
String messageFormat = "{\"price\":\"%d\",\"total\":%d}";
String message = String.format(messageFormat, price,count);
price=price/count;
WebManger.broadCast(message);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
附上前端代码:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<div style="width:400px;margin:20px auto;border:1px solid lightgray;padding:20px;text-align:center;">
当前价格为:¥<span style="color:#FF7519" id="price">10000</span>
<div style="font-size:0.9em;margin-top:20px">当前人数为: <span id="total">1</span></div>
</div>
</body>
<script type="text/javascript">
var websocket=null;
//判断浏览器是否支持websocket
if('WebSocket' in window){
websocket=new WebSocket("ws://localhost:8080/WebSocket/server");
websocket.onopen=function(){
websocket.send("客户端连接成功");
}
websocket.onerror=function(){
websocket.send("客户端连接失败");
}
websocket.onclose=function(){
websocket.send("客户端连接关闭");
}
websocket.onmessage=function(e){
send(e.data);
}
//监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常。
window.onbeforeunload = function () {
closeWebSocket();
}
}
else {
alert('当前浏览器 Not support websocket')
}
//将消息显示在网页上
function send(e) {
var obj = eval("("+e+")");
document.getElementById('price').innerHTML =obj.price;
document.getElementById('total').innerHTML = obj.total;
}
//关闭WebSocket连接
function closeWebSocket() {
websocket.close();
}
</script>
</html>