前言
我在看B站cocos教程Cocos Creator零基礎(chǔ)小白超神教程P69集遇到socketio無(wú)法正常使用的問(wèn)題。經(jīng)過(guò)百度,才了解到現(xiàn)在cocos creator實(shí)現(xiàn)客戶端和服務(wù)器之間的雙向通信是通過(guò)WebSocket 協(xié)議。WebSocket 是一種非常常用的網(wǎng)絡(luò)通信協(xié)議,本文將詳細(xì)講解 Cocos Creator 如何使用 WebSocket,包括 WebSocket 的原理和 Cocos Creator 中的代碼實(shí)現(xiàn)。
服務(wù)端
1.下載node.js,node.js下載鏈接(windows版本)
2.安裝node.js,打開(kāi)下載的安裝包,一直點(diǎn)next即可
安裝完成后,在命令行中輸入
node -v
如果出現(xiàn)版本號(hào),說(shuō)明安裝成功.如果沒(méi)有出現(xiàn)版本號(hào),可能是環(huán)境變量沒(méi)有設(shè)置好,配置環(huán)境變量可以參考視頻Cocos Creator零基礎(chǔ)小白超神教程P67Socket
3編寫服務(wù)端代碼,并以JavaScript格式保存在桌面
//JavaScript服務(wù)端
//myserver.js
const WebSocket = require('ws');
const server = new WebSocket.Server({ port: 30001 });
console.log( "server listen on 30001");
server.on('connection', (socket) => {
console.log('New client connected!');
socket.on('message', (message) => {
console.log('Received message:', message);
// 可以在此處處理收到的數(shù)據(jù)并發(fā)送回客戶端
socket.send('Server reply: ' + message);
});
socket.on('close', () => {
console.log('Client disconnected!');
});
});
4切換目錄到桌面,運(yùn)行服務(wù)端程序,可以看到服務(wù)端成功運(yùn)行
5創(chuàng)建新的cocos creator項(xiàng)目
6創(chuàng)建新節(jié)點(diǎn),新腳本(typescript),并且綁定,如圖所示,我為了看的清楚,我創(chuàng)建了new node1,new script(typeScript),new node1與圖片bg和腳本new script綁定
6編寫客戶端代碼,代碼連接連接服務(wù)端,連接成功后再控制臺(tái)打印’WebSocket connected!',然后向服務(wù)端發(fā)送消息,鼠標(biāo)點(diǎn)擊節(jié)點(diǎn),客戶端可以繼續(xù)向服務(wù)端發(fā)送消息文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-725683.html
//tpyescript
cc.Class({
extends: cc.Component,
properties: {
serverURL: 'ws://localhost:30001',
socket: null,
},
// 初始化 WebSocket 連接
initWebSocketConnection() {
this.socket = new WebSocket(this.serverURL);
this.socket.onopen = (event) => {
console.log('WebSocket connected!');
// 可以在此處發(fā)送初始數(shù)據(jù)到服務(wù)器
this.sendWebSocketData("hello");
};
this.socket.onmessage = (event) => {
console.log('Received message:', event.data);
};
this.socket.onerror = (error) => {
console.error('WebSocket error:', error);
};
this.socket.onclose = (event) => {
console.log('WebSocket closed:', event);
};
},
// 發(fā)送數(shù)據(jù)到服務(wù)器
sendWebSocketData(data) {
if (this.socket && this.socket.readyState === WebSocket.OPEN) {
this.socket.send(data);
}
},
// 關(guān)閉 WebSocket 連接
closeWebSocketConnection() {
if (this.socket) {
this.socket.close();
}
},
// 開(kāi)始時(shí)調(diào)用
onLoad() {
this.initWebSocketConnection();
},
start(){
this.node.on(cc.Node.EventType.MOUSE_DOWN,(event)=>{
this.onClickSendButton();
});
},
// 點(diǎn)擊按鈕發(fā)送數(shù)據(jù)給服務(wù)器
onClickSendButton() {
let data = 'Hello, Server!';
this.sendWebSocketData(data);
},
// 程序關(guān)閉時(shí)調(diào)用
onDestroy() {
this.closeWebSocketConnection();
},
});
7運(yùn)行結(jié)果,可以看到雙方可以互相發(fā)送消息文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-725683.html
到了這里,關(guān)于詳解 Cocos Creator 如何使用websocket的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!