【WebSocket】2-开发流程

导读:本篇文章讲解 【WebSocket】2-开发流程,希望对大家有帮助,欢迎收藏,转发!站点地址:www.bmabk.com

1.Tomcat版本

旧版本的Tomcat 不能支持WebSocket, 至少需要 7.0.47 以上才可以

2. 创建动态Web项目

菜单->File->New->Other->Web->Dynamic Web Project
在这里插入图片描述

3.复制jar

为了支持WebSocket,需要引入javaee.jar
在这里插入图片描述

4.BitCoinServer

创建BitCoinServer类,用注解@ServerEndpoint(“/ws/bitcoinServer”)把它标记为一个WebSocket Server
ws/bitcoinServer 表示有通过这个地址访问该服务

OnOpen 表示有浏览器链接过来的时候被调用
OnClose 表示浏览器发出关闭请求的时候被调用
OnMessage 表示浏览器发消息的时候被调用
OnError 表示有错误发生,比如网络断开了等等

sendMessage 用于向浏览器回发消息

其中OnOpen发生的时候,即有链接过来的时候,会把当前WebSocket Server丢在ServerManager里管理起来,这样Tomcat才知道总共有哪些Server, 方便以后进行群发

package com.how2java.bitcoin;

import java.io.IOException;
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 注解是一个类层次的注解,它的功能主要是将目前的类定义成一个websocket服务器端,
 * 注解的值将被用于监听用户连接的终端访问URL地址,客户端可以通过这个URL来连接到WebSocket服务器端
 */
@ServerEndpoint("/ws/bitcoinServer")
public class BitCoinServer {
	
	//与某个客户端的连接会话,需要通过它来给客户端发送数据
	private Session session;

	@OnOpen
	public void onOpen(Session session){
		this.session = session;
		ServerManager.add(this);     
	}
	
	public void sendMessage(String message) throws IOException{
		this.session.getBasicRemote().sendText(message);
	}

	@OnClose
	public void onClose(){
		ServerManager.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();
	}

}

5.ServerManager

ServerManager 中维护了一个线程安全的集合servers, 用于因为浏览器发起连接请求而创建的BitCoinServer.

broadCast 方法遍历这个集合,让每个Server向浏览器发消息。

其他方法很简单,不赘述

package com.how2java.bitcoin;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;

public class ServerManager {

	private static Collection<BitCoinServer> servers = Collections.synchronizedCollection(new ArrayList<BitCoinServer>());
	
	public static void broadCast(String msg){
		for (BitCoinServer bitCoinServer : servers) {
			try {
				bitCoinServer.sendMessage(msg);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
	
	public static int getTotal(){
		return servers.size();
	}
	public static void add(BitCoinServer server){
		System.out.println("有新连接加入! 当前总连接数是:"+ servers.size());
		servers.add(server);
	}
	public static void remove(BitCoinServer server){
		System.out.println("有连接退出! 当前总连接数是:"+ servers.size());
		servers.remove(server);
	}
	
}

6.BitCoinDataCenter

创建BitCoinDataCenter,使其继承HttpServlet.
标记为Servlet不是为了其被访问,而是为了便于伴随Tomcat一起启动,因为可以通过loadOnStartup一起就启动了
这个类实现了Runnable,可以在初始化方法里创建一个线程并调用之。
run 方法: 每个1-3秒就创建一个新价格,然后根据当前有多少人链接过来,进行调整价格,接着通过ServerManager广播出去。 这样浏览器就看到如如图所示的效果了

在这里插入图片描述

package com.how2java.bitcoin;

import java.util.Random;

import javax.servlet.ServletConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;

@WebServlet(name="BitCoinDataCenter",urlPatterns = "/BitCoinDataCenter",loadOnStartup=1) //标记为Servlet不是为了其被访问,而是为了便于伴随Tomcat一起启动
public class BitCoinDataCenter extends HttpServlet implements Runnable{

	public void init(ServletConfig config){
		startup();
	}
	
	public  void startup(){
		new Thread(this).start();
	}
	@Override
	public void run() {
		int bitPrice = 100000;
		while(true){
			
			//每隔1-3秒就产生一个新价格
			int duration = 1000+new Random().nextInt(2000);
			try {
				Thread.sleep(duration);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			//新价格围绕100000左右50%波动
			float random = 1+(float) (Math.random()-0.5);
			int newPrice = (int) (bitPrice*random);
			
			//查看的人越多,价格越高
			int total = ServerManager.getTotal();
			newPrice = newPrice*total;
			
			String messageFormat = "{\"price\":\"%d\",\"total\":%d}";
			String message = String.format(messageFormat, newPrice,total);
			//广播出去
			ServerManager.broadCast(message);
		}
	}
}

7.index.jsp

在WebContent下创建index.jsp
主要代码讲解:
1.判断浏览器是否支持WebSocket

    if ('WebSocket' in window) {
    

2.接受服务器回发的消息

websocket.onmessage = function (event) {
            setMessageInnerHTML(event.data);
        }
<%@ page language="java" pageEncoding="UTF-8" %>
<!DOCTYPE html>
<html>
<head>
    <title>用WebSocket实时获知比特币价格</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 style="color:silver;font-size:0.8em;margin-top:20px">以上价格纯属虚构,如有雷同,so what?</div>

    	</div>
    
</body>

<script type="text/javascript">
    var websocket = null;
    //判断当前浏览器是否支持WebSocket
    if ('WebSocket' in window) {
        websocket = new WebSocket("ws://localhost:8080/bitcoin/ws/bitcoinServer");

        //连接成功建立的回调方法
        websocket.onopen = function () {
            websocket.send("客户端链接成功");
        }

        //接收到消息的回调方法
        websocket.onmessage = function (event) {
            setMessageInnerHTML(event.data);
        }
        
        //连接发生错误的回调方法
        websocket.onerror = function () {
            alert("WebSocket连接发生错误");
        };

       //连接关闭的回调方法
        websocket.onclose = function () {
        	alert("WebSocket连接关闭");
        }

        //监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常。
        window.onbeforeunload = function () {
            closeWebSocket();
        }
        
    }
    else {
        alert('当前浏览器 Not support websocket')
    }

    //将消息显示在网页上
    function setMessageInnerHTML(innerHTML) {
    	var bitcoin = eval("("+innerHTML+")");
        document.getElementById('price').innerHTML = bitcoin.price;
        document.getElementById('total').innerHTML = bitcoin.total;
    }

    //关闭WebSocket连接
    function closeWebSocket() {
        websocket.close();
    }
    
</script>
</html>

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/117271.html

(0)
seven_的头像seven_bm

相关推荐

发表回复

登录后才能评论
极客之音——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!