一般的網絡游戲都是使用socket作為網絡通信手段,關於socket相關的知識,也有很多博客和文章有過說明,可以去搜索學習,這里就不另外說明了。
這篇博客的目的,僅僅是為了記錄如何去使用相關的工具,而不是其原理,畢竟有更多的大神比我說得清楚。記錄下來,是為了在以后再次使用中,亦或者讓閱讀到這篇博客的小伙伴,能看到最簡單最暴力的使用方法。
閑話不多說了,來,開始吧。
在nodejs服務器中,將使用nodejs-websocket這個組件來實現websocket連接。
用終端進入到nodejs服務端代碼根目錄下,用npm安裝nodejs-websocket。
npm install nodejs-websocket
在nodejs項目根目錄下新建一個websocketServer.js,用來添加相關服務端代碼。
const ws = require("nodejs-websocket");
module.exports = createServer = () => {
let server = ws.createServer(connection => {
//客戶端向服務器發送字符串時的監聽函數 connection.on("text", result => { console.log("connection.on -> text", result); }); //客戶端向服務器發送二進制時的監聽函數 connection.on("binary", result => { console.log("connection.on -> binary", result); }); //客戶端連接到服務器時的監聽函數 connection.on("connect", result => { console.log("connection.on -> connect", result); }); //客戶端斷開與服務器連接時的監聽函數 connection.on("close", result => { console.log("connection.on -> close", result); }); //客戶端與服務器連接異常時的監聽函數 connection.on("error", result => { console.log("connection.on -> error", result); }); }).listen(8182);
; return server; };
這是一個簡單的websocket模塊。接下來修改nodejs根目錄下index.js的相關代碼:
const http = require('http'); const url = require('url'); const wsServer = require('./websocketServer'); http.createServer(function(req, res){ var request = url.parse(req.url, true).query var response = { info: request.input ? request.input + ', hello world' : 'hello world' }; res.setHeader("Access-Control-Allow-Origin", "*");//跨域 res.write(JSON.stringify(response)); res.end(); }).listen(8181); wsServer();
這樣我們就創建好了一個簡單的websocket連接。
接下來修改客戶端代碼,創建一下客戶端的websocket連接。並在ui中新添加一個Label用來顯示websocket服務器返回的信息,添加一個button用來給websocket發送消息。
properties: { subButtonHttp: { default: null, type: cc.Button }, subButtonWS: { default: null, type: cc.Button }, tipLabel: { default: null, type: cc.Label }, tipLabelWS: { default: null, type: cc.Label }, input: { default: null, type: cc.EditBox } },
接下來修改一下onLoad方法,在里面添加websocket的初始化代碼:
onLoad() { this.ws = new WebSocket('ws://127.0.0.1:8182'); //開啟websocket this.ws.onopen = (event) => { console.log("event========"); console.log(event); console.log("event========"); } let that = this; //接受websocket的數據 this.ws.onmessage = (event) => { console.log("onmessage========"); console.log(event); console.log("onmessage========"); that.tipLabelWS.string = event.data; } },
再添加一個按鈕方法綁定到subButtonWS按鈕上,上傳的信息依然是輸入框中的信息:
wsRequest() { if(this.ws.readyState === WebSocket.OPEN) { this.ws.send(this.input.string); } },
當客戶端點擊按鈕發送消息給服務器時,服務器需要處理接收到的數據並分發給所有連接到websocket的客戶端。
修改服務器端websocketServer.js中的代碼:
const ws = require("nodejs-websocket"); module.exports = createServer = () => { let server = ws.createServer(connection => { //客戶端向服務器發送字符串時的監聽函數 connection.on("text", result => { console.log("connection.on -> text", result); //在這里,接收到某一個客戶端發來的消息,然后統一發送給所有連接到websocket的客戶端 server.connections.forEach((client) => { client.sendText(result); }); }); //客戶端向服務器發送二進制時的監聽函數 connection.on("binary", result => { console.log("connection.on -> binary", result); }); //客戶端連接到服務器時的監聽函數 connection.on("connect", result => { console.log("connection.on -> connect", result); }); //客戶端斷開與服務器連接時的監聽函數 connection.on("close", result => { console.log("connection.on -> close", result); }); //客戶端與服務器連接異常時的監聽函數 connection.on("error", result => { console.log("connection.on -> error", result); }); }).listen(8182); return server; };
重新啟動服務端和客戶端。當在輸入框輸入信息並點擊后,可以看到消息改變:
可以再開啟一個相同的調試頁面:
此時新打開的頁面處於初始化狀態:
在第二個頁面中輸入一些信息,並點擊提交WS按鈕:
可以看到第二個頁面的相關信息已經改變,此時再切換到第一個頁面:
可以看到,輸入框中的字還是上一次輸入的內容,但是因為websocket向所有客戶端發送了消息,label顯示的內容已經發生了改變。
經過上述步驟,就簡單的實現了多個客戶端之間產生的交互了。
下一次,我將繼續擴展上述的功能,實現一個多客戶端的聊天窗。
文章中的代碼:
客戶端: https://github.com/MythosMa/CocosCreator_ClientTest.git
服務端: https://github.com/MythosMa/NodeJS_GameServerTest.git