Chat application using CFWebsocket

793 Views Asked by At

How can we develop a facebook like chat application using cfwebsocket. There is no description about how to send an user entered message to the server and how to send that message to a particular client from the server.

<script type="text/javascript"> 
       function mymessagehandler(aevent, atoken) 
       { 
        console.log(aevent);
        console.log(atoken);
           var message = aevent.msg; 
           var txt=document.getElementById("myDiv"); 
           txt.innerHTML = txt.innerHTML + message  +"<br>"; 
       } 
</script> 
<cfwebsocket name="mycfwebsocketobject" onmessage="mymessagehandler" subscribeto="stocks" > 
<cfdiv id="myDiv"></cfdiv>

The above code just prints ok in the display. I am not sure how to pass my message inside the stocks object. Can anyone help on this? Thanks in advance

This is the stocks application that I am using

this.wschannels =      [ {name="stocks",        cfclistener="myChannelListener" }];
1

There are 1 best solutions below

0
On BEST ANSWER

This is what I have did to make my chat application work

This is the chat application

<cfwebsocket name="ChatSocket" onOpen="openHandler" onMessage="msgHandler" onError="errHandler">

This is the script

function openHandler(){
    //Subscribe to the channel, pass in headers for filtering later
    ChatSocket.subscribe('chatChannel',{name: 'TheUserName', UserID: 'TheUserID', AccountID: 'AnUniqueID' });
}

// function to send the message. we can call this when the user clicks on send message
function publish(userID){
    var msg = {
        AccountID: "AnUniqueID",
        publisher: userID,
        id: userID,
        message: document.getElementById("Name").value + " : " + document.getElementById("message").value
    };
    //When including headers, the "selector" is where you will filter who it goes to.
    var headers = {
        AccountID: "AnUniqueID",
        publisher: userID, 
        id: userID
    };
    // we can save the chat history by an ajax call here

    ChatSocket.publish('chatChannel',msg, headers);

}

// this is the receiving function
function msgHandler(message){
// if condition to display the message to the user who are sending and receiving
    if(message.data !== undefined && message.data.message !== undefined && (message.data.id == '#session.userID#' || message.data.publisher == '#session.userID#')) { 
        var data = message.data.message;
        console.log(data);
        //showing the message
        var txt=document.getElementById("myDiv");
        txt.innerHTML+= data + "<br>"; 
    } 
}

function errHandler(err){
    console.log('err');
    console.log(err);
}