过了一会儿,我得到了Google Channel API
工作的第一部分。现在我在从 JavaScript 客户端向服务器发送消息时遇到了一些问题。这是Google Channel API
连接的 servlet:
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
UserService userService = UserServiceFactory.getUserService();
User user = userService.getCurrentUser();
if (user != null) {
ChannelService channelService = ChannelServiceFactory.getChannelService();
String token = channelService.createChannel(user.getUserId());
FileReader reader = new FileReader("index.html");
CharBuffer buffer = CharBuffer.allocate(16384);
reader.read(buffer);
reader.close();
String index = new String(buffer.array());
index = index.replaceAll("\\{\\{ token \\}\\}", token);
resp.setContentType("text/html");
resp.getWriter().write(index);
} else {
resp.sendRedirect(userService.createLoginURL(req.getRequestURI()));
}
index.html
如下所示:
<script src="/_ah/channel/jsapi"></script>
<body>
<script type="text/javascript">
onOpened = function() {
alert("opened");
}
var token = "{{ token }}";
var channel = new goog.appengine.Channel(token);
var handler = {
'onopen' : onOpened,
'onmessage' : onMessage,
'onerror' : function() {
},
'onclose' : function() {
}
};
var socket = channel.open(handler);
socket.onopen = onOpened;
socket.onmessage = onMessage;
function sendMessage() {
// Send JSON object to server
}
</script>
<h1>Google Test Channel API</h1>
<form>
<input type="button" value="Send" onclick="sendMessage();">
</form>
</body>
如果我加载应用程序,我会收到opened
警报,我相信连接正常。现在,如果有人单击该按钮,我想向服务器发送一条消息。
我读到我必须将 XMLHttpRequest 函数与 POST 或 GET 一起使用。但我不会传递一个新的 url,我只会传递一个值。有没有办法将 JSON 对象发送到服务器?
就像是:
{
"message": "This is a JavaClient message!"
}