SpringMVC 如何实现将消息的websocket

哥们,你是不是也在做javaweb,但是javaweb我们平时大部分时间都是使用http协议,也就是浏览器实现请求,然后后台返回数据,但是这样不能满足你强大的野心啊,你想的时候后台可以向前台推送消息,你的野心大了,自然要学习,于是你看websocket,也许你并不是多了解这是怎样的一个东西,,那么我告诉你,你找对了,websocket确实是能够实现后台向前台web端推送消息

那么怎样推送,网上这样的例子也不少,我也是看了很久,大家都写的很好,但是你感觉SpringMVC是不是需要配置什么东西,我看人家都配置了,可能需要配置吧,但是也不确定,这个随你自己关键是前台和后台调通就行了呗,,哈哈,不说这些废话了,我直接上代码吧:

<!DOCTYPE html>
<html>
<head>
<title>websocket example</title>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=8,9,10" />
<script type="text/javascript" src="../js/jquery-1.11.0.min.js"></script>
<script type="text/javascript" src="../js/sockjs-0.3.min.js"></script>
</head>
<script type="text/javascript">
	$(function() {
		var websocket = null;
		var url = "ws://localhost:8080/Shopping/websocket";

		if ('WebSocket' in window) {
			websocket = new WebSocket("ws://localhost:8080/Shopping/websocket");
		} else if ('MozWebSocket' in window) {
			websocket = new MozWebSocket(
					"ws://localhost:8080/Shopping/websocket");
		} else {
			websocket = new SockJS(
					"http://localhost:8080/Shopping/sockjs/websocket");
		}
		//打开websocket
		websocket.onopen = function() {
			websocket.send("helloworld");
			console.log("websocket链接成功");
		}
		//接收到消息
		websocket.onmessage = function(event) {
			console.log('Received: ' + event.data);
		};
		//关闭的时候
		websocket.onclose = function(event) {
			console.log('Info: connection closed.');
			console.log(event);
		};
		//发生错误的时候
		websocket.onerror = function(evnt) {
			console.log("  websocket.onerror  ");
		};
		//发送消息

	});
</script>
<body>
</body>
</html>

上面是前台的html网页,有的在页面前面还加什么jsp之类的标签,告诉你,那样也是没有错误的,但是我也尝试了,至少对我而言帮助是不大的,

前台好了,那么后台改怎样来写:

package com.wdg.controller;

import java.io.IOException;
import java.util.concurrent.CopyOnWriteArraySet;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;

/**
 * @ServerEndpoint 注解是一个类层次的注解,它的功能主要是将目前的类定义成一个websocket服务器端,
 *                 注解的值将被用于监听用户连接的终端访问URL地址,客户端可以通过这个URL来连接到WebSocket服务器端
 */
@ServerEndpoint("/websocket")
public class WebSocketServer {
	// 静态变量,用来记录当前在线连接数。应该把它设计成线程安全的。
	private static int onlineCount = 0;

	// concurrent包的线程安全Set,用来存放每个客户端对应的MyWebSocket对象。若要实现服务端与单一客户端通信的话,可以使用Map来存放,其中Key可以为用户标识
	private static CopyOnWriteArraySet<WebSocketServer> webSocketSet = new CopyOnWriteArraySet<WebSocketServer>();

	// 与某个客户端的连接会话,需要通过它来给客户端发送数据
	private Session session;

	/**
	 * 连接建立成功调用的方法
	 * 
	 * @param session
	 *            可选的参数。session为与某个客户端的连接会话,需要通过它来给客户端发送数据
	 */
	@OnOpen
	public void onOpen(Session session) {
		this.session = session;
		webSocketSet.add(this); // 加入set中
		addOnlineCount(); // 在线数加1
		System.out.println("有新连接加入!当前在线人数为" + getOnlineCount());
	}

	/**
	 * 连接关闭调用的方法
	 */
	@OnClose
	public void onClose() {
		webSocketSet.remove(this); // 从set中删除
		subOnlineCount(); // 在线数减1
		System.out.println("有一连接关闭!当前在线人数为" + getOnlineCount());
	}

	/**
     * 收到客户端消息后调用的方法
     * @param message 客户端发送过来的消息
     * @param session 可选的参数
     */
    @OnMessage
    public void onMessage(String message, Session session) {
        System.out.println("来自客户端的消息:" + message);
        //群发消息
        for(WebSocketServer item: webSocketSet){
            try {   
                item.sendMessage("折旧的心");
            } catch (IOException e) {
                e.printStackTrace();
                continue;
            }
        }

	}

	/**
	 * 发生错误时调用
	 * 
	 * @param session
	 * @param error
	 */
	@OnError
	public void onError(Session session, Throwable error) {
		try{
			
		}catch(Exception e){
			System.out.println("发生错误:你的主机中的软件中止了一个已建立的连接");
		}
	}

	/**
	 * 这个方法与上面几个方法不一样。没有用注解,是根据自己需要添加的方法。
	 * 
	 * @param message
	 * @throws IOException
	 */
	public void sendMessage(String message) throws IOException {
		this.session.getBasicRemote().sendText(message);
		// this.session.getAsyncRemote().sendText(message);
	}

	public static synchronized int getOnlineCount() {
		return onlineCount;
	}

	public static synchronized void addOnlineCount() {
		WebSocketServer.onlineCount++;
	}

	public static synchronized void subOnlineCount() {
		WebSocketServer.onlineCount--;
	}
}

这样大概也就是好了,其实我没有做任何的配置,获取也不需要做任何的配置,两个页面给大家了,一个是java的后台,一个是前台的HTML文件,大家直接拷过去,直接刷新网页然后后台控制台打印出来消息:


如果你看到这样的提示恭喜你success

希望对你有所帮助


猜你喜欢

转载自blog.csdn.net/datouniao1/article/details/80571588