How to send text to websocket server using send()


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:


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 =;

function wsClose(message) {
    console.log("Connection Closed");

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

    extends: cc.Component,

    properties: {
      // websocket
        webSocket: null,


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

    start: function () {
        this.webSocket.onopen = function(message){
        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.