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