1: 掌握websocket基本使用;
2: 掌握socket.io基本使用;
websocket
1: creator只支持websocket, h5的标准也只支持websocket;
2: websocket 底层是 tcp socket, 基于tcp socket上建立了连接,收发数据的标准,保证了用户收到的数据和发到的数据是一致的,不用考虑粘包等问题,websocket协议已经解决了;
3: websocket的使用方式:
1>new WebSocket(url); 服务器对应的url: “ws://127.0.0.1:6081/ws”, ip + port
2> 支持的数据: 文本数据类型与二进制数据类型;
sock.binaryType = "arraybuffer"/”Blob”; 支持arraybuffer和Blob类型,一般配置成arraybuffer,根据服务器而定;
3>配置好websocket的回掉函数:
onopen(event), onmessage(event), onclose(event), onerror(event),
4>不用了关闭socket或收到服务器关闭遇到错误: close方法;
4: 基于node.js来测试下websocket, node.js见服务器课程;
TCP的粘包现象
客户端代码
// websocket.js 导出的自己封装的websocket模块
var websocket = {
sock: null, // 连接的socket 对象 WebSocket, h5标准对象;
// 网络连接成功了以后调用
on_open: function(event) {
// test
this.send_data("HelloWorld");
// end
},
// 客户端收到数据的时候
on_message: function(event) {
console.log("#####", event.data);
},
// 客户端收到socket 关闭的时间的时候调用;
on_close: function (event) {
this.close();
},
on_error: function (event) {
this.close();
},
close: function() {
if (this.sock != null) {
this.sock.close(); // 关闭socket
this.sock = null;
}
},
// 连接函数,
connect: function(url) {
this.sock = new WebSocket(url); // h5标准的websocket对象
this.sock.binaryType = "arraybuffer"; // 配置接受二进制的数据类型,与服务器保持一次, "Blob"
// 为这个websocket对象制定对应的回掉函数;
this.sock.onopen = this.on_op

本文介绍了Cocos Creator中WebSocket和Socket.IO的基础使用,包括WebSocket的TCP粘包现象解决、创建与配置,以及Socket.IO的事件驱动模式和在Cocos Creator中的注意事项与实践操作。

2893

被折叠的 条评论
为什么被折叠?



