我正在尝试使用Google App Engine的渠道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 }}')
的一些示例感到困惑。
{{ }}
中附有什么内容?
答案 0 :(得分:0)
请注意,令牌是一个识别您的页面的TOKEN KEY。首先在页面中初始化令牌,如:
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.');
};
..创建这样的函数
答案 1 :(得分:0)
除了使用正确的令牌之外,你的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();
};
答案 2 :(得分:0)
在javascript中
function onMessage(msg)
{
var msg1=msg.data;
$('textarea').val($('textarea').val()+msg1);
}
在后端
ChannelService channelService = ChannelServiceFactory.getChannelService();
channelService.sendMessage(new ChannelMessage(clientid,message));