无法在 cfwebsocket JS 函数发布上获取额外的参数值

Cannot get the extra argument value on cfwebsocket JS function publish

我正在尝试使用 cfwebsocket 创建客户端到客户端的聊天应用程序。我参考了 adobe 示例。在该示例中,我们将一个额外的参数传递给发布函数。所以我将接收者 ID 传递给发布函数,但无法在 msgHandler 函数中获取该值。

<cfoutput>
    <cfif !structkeyexists(session,'userName')>
        <cflocation url="index.cfm?msg=Please login first" addtoken="false">
    </cfif>
    <cfdump var="i am chat.cfm" />
    <a href="logout.cfm" style="float:right">Logout</a>
    <cfwebsocket name="myworld" onMessage="msgHandler" onOpen="openHandler"/>

    <script>
        var msgHandler = function(message){
            // Get data from the recieved message token
            var data = message.data;
            console.log(message.data.to);
            if(data){
                // If data is present write it to the div
                var txt=document.getElementById("myDiv");
                txt.innerHTML+= data + "<br>";
            }
        }

        var sayHello = function(){
            uname = document.getElementById("username").value;
            receiver = document.getElementById("selectUser").value;
            //var myData = {publishedBy: ''+uname, receiver:''+receiver}
            // Calling authenticate from client side. Calling this
            //function will invoke onWSAuthenticate from Application.cfc

            myworld.authenticate(uname,"password");
            myworld.subscribe("chat");
            // Client says Hello World
            myworld.publish("chat","Hello World! WebSocket is here !!",{to:receiver});
        }

        var openHandler = function(){
            // do nothing
        }
    </script>
    <input type="hidden" name="userName" id="username" value="#session.userName#">
    <input  id="hello" type="button" value="Say Hello!" onclick="sayHello();">

    <div id="myDiv"></div>

    <cfset users = Application.usersDAO.read()>
    <select name="user" id="selectUser">
        <option value="0">Select User</option>
        <cfloop query="users">
            <option value="#id#">#username#</option>
        </cfloop>
    </select>   
</cfoutput>

您应该像 json 对象一样传递消息和额外参数。

var sayHello = function()
  {
   uname = document.getElementById("username").value;
   userID = document.getElementById("userID").value;
   receiverID = document.getElementById("ToUser").value;
   receiverName = document.getElementById("ToUserName").value;
   // Calling authenticate from client side. Calling this function will invoke onWSAuthenticate from Application.cfc
   myworld.authenticate(uname,"password");
   // Client says Hello World

   // console.log($('#input').val())
   msg = {'username': uname, 'userID' : userID, 'chat': $('#input').val().trim(), 'to':receiverID, 'receiverName' : receiverName };
   myworld.publish("world",msg);
   $('#input').val('');
  }

在 msgHandler 函数中,您将获得 message.data.to 和 message.data.userId。您将 userId 存储在 msgHandler 内的会话范围内,您将比较会话 userID 和 message.data.to。如果两者相同,您将在您的聊天 window 上附加您的消息。