我正在尝试将 Cocos2dx 中的套接字与 Nodejs 中的服务器连接,但它无法按预期工作。 这是我的代码:
在HelloWorldScene.h中
class HelloWorld : public cocos2d::Layer, public SocketIO::SIODelegate
{
public:
...
// socket.io even\vent listener
void onReceiveEvent(SIOClient* client, const std::string& data);
// SIODelegate
virtual void onConnect(SIOClient* client);
virtual void onMessage(SIOClient* client, const std::string& data);
virtual void onClose(SIOClient* client);
virtual void onError(SIOClient* client, const std::string& data);
CREATE_FUNC(HelloWorld);
protected:
private:
int index;
SIOClient* _client;
TextField* editBox;
};
在HelloWordScene.cpp中
bool HelloWorld::init()
{
//////////////////////////////
// 1. super init first
if (!Layer::init())
{
return false;
}
Size visibleSize = Director::getInstance()->getVisibleSize();
Vec2 origin = Director::getInstance()->getVisibleOrigin();
// connect to server
_client = SocketIO::connect("http://192.168.0.105:3010", *this);
return true;
}
void HelloWorld::onConnect(SIOClient* client) {
// SocketIO::connect success
}
void HelloWorld::onMessage(SIOClient* client, const std::string& data) {
// SocketIO::send receive
}
void HelloWorld::onClose(SIOClient* client) {
// SocketIO::disconnect success
}
void HelloWorld::onError(SIOClient* client, const std::string& data) {
// SocketIO::failed
}
还有我的服务器(在浏览器中连接运行良好)
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.get('/', function (req, res) {
res.sendfile('index.html');
});
var handleClient = function (socket) {
console.log('connection');
//testing simple message
socket.on('message', function (msg) {
console.log('Default namespace received message: ' + msg);
socket.send('echo: ' + msg);
});
var listen = function() {
http.listen(3010);
console.log('listening on *:3010');
}
module.exports.listen = listen;
这个问题有什么解决办法吗?我已经尝试了很多版本的 SocketIO 但到目前为止没有任何效果。
我认为cocos实现的SocketIO与node版本不兼容。尝试通过添加此来允许向后兼容
var io = require('socket.io')(http, {allowEIO3: true});