實作遊戲公告功能
實作功能:遊戲管理裡釋出遊戲公告,其它遊戲玩家頁面能夠馬上接受到遊戲公告資訊。
下面直接上代碼案例,這裡主要展示關鍵代碼,底部有源碼。
一、案例
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】