1

我正在尝试使用 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>
4

1 回答 1

0

您应该像 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。您将在 msgHandler 内的会话范围内存储 userId,您将比较会话 userID 和 message.data.to。如果两者相同,您将在聊天窗口中显示您的消息。

于 2016-06-14T18:03:08.953 回答