Problem socket.emit Cocos Creator

Hello, this is my code:

server.js
> var express = require(‘express’);
> var app = express();
> var http = require(‘http’).Server(app);
> var io = require(‘socket.io’)(http);

>     app.use(express.static(__dirname + '/public'));

>     io.on('connection', function(socket) {
>     	console.log('dispositivo connesso');
>     	socket.emit('connected', 'connesso');
>     	socket.on('message', function(messaggio){
>     		console.log(messaggio);
>     	});
>     	
>     });

>     http.listen(3000, function() {
>     	console.log('listening on : 3000')
>     });

app.js
> cc.Class({
> extends: cc.Component,

>     properties: {
>         label: {
>             default: null,
>             type: cc.Label
>         },
>         // defaults, set visually when attaching this script to the Canvas
>     },

>     // use this for initialization
>     onLoad: function () {
>         let self = this;
>         if (cc.sys.isNative) {
>             window.io = SocketIO;
>         } else {
>             require('socket.io');
>         }
>         
>         var socket = io.connect('http://localhost:3000');
>         
>         socket.on('connected', function (msg) {
>             self.label.string = msg;
>         });
>         var messaggio = 'Hello World';
>         socket.emit('messagge', messaggio);
>         
>     },

>     // called every frame
>     update: function (dt) {

>     },
> });

Launching the application with “Browser” works perfectly well.

Launching the application with “Simulator”, socket.on works, but socket.emit does not work.

In the console I have this error:

Simulator: JSB SocketIO.emit method called
Simulator: JSB SocketIO emit event ‘messagge’ with payload: Hello World
Simulator: JSB SocketIO::SIODelegate->onError method called from native with data: Client not yet connected
Simulator: JSB SocketIO::SIODelegate->fireEventToScript method called from native with name ‘error’ data: Client not yet connected

How can I fix the problem?

Can not anyone help me? please?

You can try this code:

socket.on('connected', function (msg) {
    self.label.string = msg;
    var messaggio = 'Hello World';
    socket.emit('messagge', messaggio);
});
1 Like

Thanks, it works!! :slight_smile: