Creator版本:v3.8.3
socketIO是socket的一个封装
cocos里集成了websocket但是没有socketIO
- 下载依赖文件
首先需要下载socketIO代码,版本要和后端保持一致
能npm下载最好npm install socket.io-client@version
(需要指定版本)
但我这一直超时,所以就直接去下载代码 - 下载后复制到项目目录中(我放到了libs下)
- 然后需要配置为插件
在脚本的属性检查器选择【导入为插件】,并根据需求配置
- 然后就开始写连接代码吧(io会报红,不用管!!)
我创建了SocketIO.ts脚本(可以根据自己项目定制)
import { GameEvent } from '../game/common/config/GameEvent';
class ScoketIO {socket: any;/*** 连接socketIO* @param url 地址* @param call 连接成功回调*/connect(url: string, call?: Function) {if (this.socket && this.socket.connected) return;console.log("Starting connection to socket.io server");let socket = io(url,{withCredentials: true,extraHeaders: {"my-custom-header": "abcd",},transports: ['websocket', 'polling', 'flashsocket']});console.log(socket.connected); // socket是否与服务器连接console.log(socket.disconnected); // socket是否与服务器断开连接// client-sidesocket.on("connect", () => {console.log(`Socket.ID: ${socket.id}`);if (call) call();});socket.on("disconnect", (reason: any) => {console.log(socket.connected);console.log("断开连接-disconnect", reason);})socket.on("error", (err: any) => {console.log("错误-error", err);})// 连接错误socket.on("connect_error", (err: any) => {console.log("连接错误-connect_error:", err);});// 连接超时socket.on("connect_timeout", (data: any) => {console.log("连接超时-connect_timeout", data);});socket.on(MsgEvent.StartGame, (data: any) => {console.log(MsgEvent.StartGame, data);// 派发事件MsgEvent.StartGame})this.socket = socket;}send(key: string, msg: any) {if(this.socket && this.socket.connected){console.log("========socket send", key, msg)this.socket.emit(key, msg);}}close() {if(this.socket && this.socket.connected){this.socket.connected = false;this.socket.disconnect();this.socket = null;}}
}/**响应事件类型 */
export enum MsgEvent {// 开始游戏StartGame = "StartGame",
}
export let socketIO = new ScoketIO();
- 还有一个测试工具
目前还没用