我正在尝试使用cfwebsocket创建客户端到客户端聊天应用程序。我引用了adobe示例。在该示例中,我们将一个额外的参数传递给publish函数。所以我将接收者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>
答案 0 :(得分: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。您将把userId存储在msgHandler中的会话范围内,您将比较会话userID和message.data.to。如果两者相同,您将在聊天窗口上显示您的消息。