实现游戏公告功能
实现功能:游戏管理里发布游戏公告,其它游戏玩家页面能够马上接受到游戏公告信息。
下面直接上代码案例,这里主要展示关键代码,底部有源码。
一、案例
1、pom.xml文件
主要是添加springBoot和webSocket相关jar包,和一些辅助工具jar包(注意我采用的是springBoot2.1.0版本
pom.xml
2、WebSocketConfig
这个是websocket配置中心,配置一些核心配置。
import org.springframework.context.annotation.Configuration; import org.springframework.messaging.simp.config.MessageBrokerRegistry; import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker; import org.springframework.web.socket.config.annotation.StompEndpointRegistry; import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer; @Configuration //注解用于开启使用STOMP协议来传输基于代理(MessageBroker)的消息,这时候控制器(controller)开始支持@MessageMapping,就像是使用@requestMapping一样。 @EnableWebSocketMessageBroker public class WebSocketConfig implements WebSocketMessageBrokerConfigurer { /** * 注册端点,发布或者订阅消息的时候需要连接此端点 * setAllowedOrigins 非必须,*表示允许其他域进行连接 * withSockJS 表示开始sockejs支持 */ public void registerStompEndpoints(StompEndpointRegistry registry) { registry.addEndpoint("/endpoint-websocket").setAllowedOrigins("*").withSockJS(); } /** * 配置消息代理(中介) * enableSimpleBroker 服务端推送给客户端的路径前缀 * setApplicationDestinationPrefixes 客户端发送数据给服务器端的一个前缀 */ @Override public void configureMessageBroker(MessageBrokerRegistry registry) { registry.enableSimpleBroker("/topic"); registry.setApplicationDestinationPrefixes("/app"); } }
3、GameInfoController
管理员发布公告消息对应的接口
/* *模拟游戏公告 */ @Controller public class GameInfoController { //@MessageMapping和@RequestMapping功能类似,用于设置URL映射地址,浏览器向服务器发起请求,需要通过该地址。 //如果服务器接受到了消息,就会对订阅了@SendTo括号中的地址传送消息。 @MessageMapping("/gonggao/chat") @SendTo("/topic/game_chat") public OutMessage gameInfo(InMessage message){ return new OutMessage(message.getContent()); } }
4、管理员页面和用户页面
admin页面和user页面唯一的区别就是管理员多一个发送公告的权限,其它都一样,user1和user2完全一样。
(1)admin.html
admin.html
(2)user1.html
user1.html
(3)user2.html
user2.html
5.app.js
这个是客户端连接websocket的核心,通过html的点击事件来完成。
var stompClient = null; //这个方法仅仅是用来改变样式,不是核心 function setConnected(connected) { $("#connect").prop("disabled", connected); $("#disconnect").prop("disabled", !connected); if (connected) { $("#conversation").show(); } else { $("#conversation").hide(); } $("#notice").html(""); } //1、建立连接(先连接服务端配置文件中的基站,建立连接,然后订阅服务器目录消息 function connect() { //1、连接SockJS的endpoint是“endpoint-websocket”,与后台代码中注册的endpoint要一样。 var socket = new SockJS('/endpoint-websocket'); //2、用stom进行包装,规范协议 stompClient = Stomp.over(socket); stompClient.connect({}, function (frame) { //3、建立通讯 setConnected(true); console.log('Connected: ' + frame); //4、通过stompClient.subscribe()订阅服务器的目标是'/topic/game_chat'发送过来的地址,与@SendTo中的地址对应。 stompClient.subscribe('/topic/game_chat', function (result) { console.info(result) showContent(JSON.parse(result.body)); }); }); } //2、关闭连接 function disconnect() { if (stompClient !== null) { stompClient.disconnect(); } setConnected(false); console.log("Disconnected"); } //3、游戏管理员发送公告信息(这个也是游戏用户所没有功能,其它都一样) function sendName() { //1、通过stompClient.send 向/app/gonggao/chat 目标 发送消息,这个是在控制器的@messageMapping 中定义的。(/app为前缀,配置里配置) stompClient.send("/app/gonggao/chat", {}, JSON.stringify({'content': $("#content").val()})); } //4、订阅的消息显示在客户端指定位置 function showContent(body) { $("#notice").append("<tr><td>" + body.content + "</td> <td>"+new Date(body.time).toLocaleString()+"</td></tr>"); } $(function () { $("form").on('submit', function (e) { e.preventDefault(); }); $( "#connect" ).click(function() { connect(); }); $( "#disconnect" ).click(function() { disconnect(); }); $( "#send" ).click(function() { sendName(); }); });
6、查看运行结果
7、小总结
首先很明显看的出,websocket最大的优点,就是可以服务端主动向客户端发送消息,而此前http只能是客户端向服务端发送请求。
gitHub源码:https://github.com/yudiandemingzi/websocket
想太多,做太少,中间的落差就是烦恼。想没有烦恼,要么别想,要么多做。中校【19】