我正在使用 Atmosphere 框架 2.0.0.RC5 使用 websocket 功能扩展我的 Web 应用程序,并遇到了一些奇怪的错误“Websocket 失败。降级到彗星并重新发送',我无法逃脱。
我使用了一个 websocket 聊天示例作为我的起点:https ://github.com/Atmosphere/atmosphere-samples/tree/master/samples/websocket-chat
该应用程序具有 html+js 客户端和 java 后端。
后端
- 启用 NIO 协议的 Tomcat 7.0.42
- 带有 Spring 和 Atmosphere servlet 的 Web 模块 v3.0
- 自定义 CORS 过滤器以允许大气标头
- 服务器记录每条收到的消息
(多余的代码省略)
public void onTextMessage(WebSocket webSocket, String message) throws IOException {
logger.info("Message received: " + message);
webSocket.broadcast(mapper.writeValueAsString(mapper.readValue(message, Data.class)));
}
客户
index.html
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript" src="js/lib/jquery.atmosphere-2.0.2.js"></script>
<script type="text/javascript" src="js/aimpl.js"></script>
aimpl.js
$(function() {
"use strict";
var socket = $.atmosphere;
var request = {
url: 'http://localhost:8181/services/echo',
transport: "websocket",
contentType: "application/json",
//connectTimeout: '300000',
fallbackTransport: 'long-polling',
enableXDR: true,
logLevel: 'debug'
};
request.onMessage = function (response) {
console.log(response.responseBody)
};
request.onOpen = function(response) {
console.log('Atmosphere connected using ' + response.transport);
};
request.onReconnect = function (request, response) {
console.log("reconnecting...");
};
request.onError = function(response) {
console.log('an error has occured.');
};
var channel = socket.subscribe(request);
channel.push(JSON.stringify({ author: 'me', message: 'hello from websocket!' }));
});
当我打开“index.html”时,我在控制台中看到一个错误(jquery.atmosphere-2.0.2.js 第 1097 行),并且服务器日志中没有消息:
令人惊讶的是,当我直接在控制台中输入时它会起作用:
并被服务器记录,所以我假设服务器部分很好:
我猜这是一个 javascript 问题,但我不是 100% 确定。我玩connectTimeout
参数没有运气。任何想法为什么它在脚本中不起作用?