How to send text to websocket server using send()

Hi,

The websocket is done handshaking but it seems like I couldn’t send data in the form of strings to my java server. I could however send data from the server back. I’m sure that the websocket library in java takes care of onmessage, and this error pops up in the console when I run my game.js in the canvas in simulator mode:

STACK:
[0]wsGetMessage@dst/assets/Script/game.js:34
[1]webSocket.onmessage@dst/assets/Script/game.js:71

Uncaught TypeError: Cannot read property ‘send’ of undefined

here’s the code I have so far in game.js:

function wsOpen(message) {
    //
};

function wsGetMessage(message) {
    var price = message.data;
    console.log(price);
    this.webSocket.send("hello");
};

function wsClose(message) {
    console.log("Connection Closed");
    this.webSocket.close();
};

function wsError(message) {
    console.log("Error in Websocket Connection");
};

cc.Class({
    extends: cc.Component,

    properties: {
      // websocket
        webSocket: null,
    },

    // LIFE-CYCLE CALLBACKS:

    onLoad: function () {
      // what is the url?
      // try catch?
        this.webSocket = new WebSocket("ws://localhost:7500");
    },

    start: function () {
        this.webSocket.onopen = function(message){
          this.webSocket.send("hello");
        };
        this.webSocket.onmessage = function(message){ wsGetMessage(message);};
        this.webSocket.onclose = function(message){ wsClose(message);};
        this.webSocket.onerror = function(message){ wsError(message);};
    },

    // update (dt) {},
});

I can ask engineering to have a look. What version of Creator are you using?

I’m using version 2.4.6

Maybe you can use nodejs-websocket

Does this mean that my server has to be written in javascript as well? Also, I installed nodejs-websocket using npm install nodejs-websocket in my project root folder, but when I put:

var WebSocketClient = require('nodejs-websocket').client;
var client = new WebSocketClient();

the “client” part in require(‘nodejs-websocket’).client is red, but I see in other code snippets it is blue. Also the error appears in console:

ERROR: Uncaught TypeError: WebSocketClient is not a constructor

In your original code, I think the problem is potentially that this is not valid because of the way the callback is handled. I definitely send both string and binary data over websockets. Try making a local variable like var self = this and then reference self in your callback. That error is saying this.webSocket is not defined so I think that’s the problem.