[英]onmessage Google App Engine (Java) Channel API
我正在尝试使用Google App Engine的Channel API。
JavaScript / JQuery:
$(document).ready(function(){
alert('ready');
$.post('/token', function(data) {
alert('token:' + data['token']);
openChannel( data['token'] );
});
$.post('/chat', function(data) {
alert('chat:' + data['users'].length);
});
});
onMessage = function(message) {
alert(message);
}
onSocketError = function(error){
alert("Error is <br/>"+error.description+" <br /> and HTML code"+error.code);
};
onSocketOpen = function() {
// socket opened
};
onSocketClose = function() {
alert("Socket Connection closed");
};
openChannel = function(token) {
alert('open channel');
var channel = new goog.appengine.Channel( token );
var socket = channel.open();
socket.onopen = onSocketOpen;
socket.onmessage = onMessage;
socket.onerror = onSocketError;
socket.onclose = onSocketClose;
};
问题是警报(消息)不会触发。 我的代码很幸运吗?
我对某些在服务器端具有"\\\\{\\\\{ token \\\\}\\\\}"
且在javascript中使用channel = new goog.appengine.Channel('{{ token }}')
的示例感到困惑。
{{ }}
什么?
请注意,令牌是识别您页面的令牌密钥。 首先在页面中初始化令牌,例如:
ChannelService channelService = ChannelServiceFactory.getChannelService();
String token = channelService.createChannel("sample");
现在
var token ="<%=token %>";// This will creaete unique identifier(some id created by google api + ur key)
channel = new goog.appengine.Channel('<%=token%>');
socket = channel.open();
socket.onopen = function () {
var connected = true;
sendMessage('<b>'+userName+'</b> Logged in.');
};
..创建类似的功能
除了使用正确的令牌之外,您的onMessage函数不会触发,因为这是在您从服务器向客户端发送消息时发生的:
channelService.sendMessage(new ChannelMessage(channelKey, "Hello World"));
您可以设置XMLHttpRequest以便从客户端与服务器端进行通信,在该服务器端可以运行之前的Java代码,例如:
sendMessage = function(path, param) {
var xhr = new XMLHttpRequest();
xhr.open('GET', 'path + '&' + param', true);
xhr.send();
};
在JavaScript中
function onMessage(msg)
{
var msg1=msg.data;
$('textarea').val($('textarea').val()+msg1);
}
在后端
ChannelService channelService = ChannelServiceFactory.getChannelService();
channelService.sendMessage(new ChannelMessage(clientid,message));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.