Hamzeh Hirzallah
Hamzeh Hirzallah

Reputation: 263

connect to coldfusion websocket from HTML page

I want to open a web-socket to a ColdFusion 2016 server, but I want to open it from HTML page (not cfm) so I don't have the option to use cfwebsocket tag. what I want is a replacement for it.. I have tried the following code

var webSocket_IP = '192.168.1.223';
        var chatSocket = new WebSocket("ws://"+webSocket_IP+":8579/cfusion/cfusion");                   

        chatSocket.onopen = function () {
            alert('OPEN');
        };
        chatSocket.onmessage = function () {
            alert('a message was recieved');
        };
        chatSocket.onError = function () {
            alert('Error');
        };

the problem is that I cant open the connection and the onOpen method does not run

another problem is that when I want to subscribe to any channel

chatSocket.subscribeTo('chat');

I keep getting the following error

TypeError: chatSocket.subscribeTo is not a function

Upvotes: 2

Views: 1082

Answers (2)

Michael Warner
Michael Warner

Reputation: 4217

For clarification on Hamzeh's Answer.

How to establish a connection

var chatSocket = new WebSocket("ws://"+webSocket_IP+":8579/cfusion/cfusion");  

How to subscribe to a channel

chatSocket.send(
  JSON.stringify( {
    appName: "customoptionexample1", //App Name
    authKey: "739CAAF6CA8CA73DCCDB9305225F7D48",
    ns: "coldfusion.websocket.channels",
    subscribeTo: "bidchannel", //Channel subscribing to
    type: "welcome"
  } )
);

How to Send Data

chatSocket.send(
  JSON.stringify( {
    "ns": "coldfusion.websocket.channels",
    "type": "publish",
    "channel": "bidchannel", // Channel Name
    "appName": "customoptionexample1", //App Name
    "data": "Bid placed by adfadfadf Amount 66",
    "customOptions": {
      "value": "66"
    }
  } )
);

Setting up normal web socket callbacks

chatSocket.onopen = function() {
  console.log( 'opened' );
};
chatSocket.onclose = function() {
  console.log( 'onclose' );
};
chatSocket.onerror = function() {
  console.log( 'onerror' );
};
chatSocket.onmessage = function( event ) {
  //This parses the data and just prints the data and not the meta data.
  console.log( 'onmessage', JSON.parse(event.data).data ); 
};

Upvotes: 3

Hamzeh Hirzallah
Hamzeh Hirzallah

Reputation: 263

in case someone stumbled with the same issue , I have found the solution first connect to coldfusion web socket path

var chatSocket = new WebSocket("ws://"+webSocket_IP+":8579/cfusion/cfusion");  

then write the following command on the web socket object to subscribe to any channel

{"ns":"coldfusion.websocket.channels","type":"welcome","subscribeTo":"CHANNELNAME","appName":"APPNAME"}

and in case you want to write a message use the following:

{"ns":"coldfusion.websocket.channels","type":"publish","channel":"CHANNELNAME","data":"hi","appName":"APPNAME"}

Upvotes: 2

Related Questions