我遇到了以下问题:我正在运行带有socket.io的JAVA服务器(netty socket.io - https://github.com/mrniko/netty-socketio) - 我试图通过不同的Web服务器访问此服务器的JavaScript。
对于测试,我试图让Demo Chat运行(https://github.com/mrniko/netty-socketio-demo)。
问题现在是我不断得到以下
XMLHttpRequest cannot load http://myserver/socket.io/1/?t=1400445162388. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'myclient.com' is therefore not allowed access.
所以最大的问题是:如何允许访问我的java服务器?我找到了一些解决方案,说要添加'标题',但我不知道在哪里放。那是否会进入socket.io服务器代码?
我想我需要这样的东西,放在JAVA服务器上的某个地方:
response.setHeader("Access-Control-Allow-Origin", "*");
这是启动服务器的代码:
Configuration config = new Configuration();
config.setHostname("localhost");
config.setPort(80);
final SocketIOServer server = new SocketIOServer(config);
//ChatObject wurde extra implementiert, ggf. loeschen
server.addJsonObjectListener(ChatObject.class, new DataListener<ChatObject>() {
@Override
public void onData(SocketIOClient client, ChatObject data, AckRequest ackRequest) throws Exception {
// broadcast messages to all clients
server.getBroadcastOperations().sendJsonObject(data);
}
});
server.start();
这是从服务器获取的输出:
error: The specified resource was not found: /static/flashsocket/WebSocketMain.swf
error: The specified resource was not found: /static/flashsocket/WebSocketMainInsecure.swf
info: Session store / pubsub factory used: {}MemoryStoreFactory (local session store only)
info: SocketIO server started at port: {}80
非常感谢任何帮助!谢谢
答案 0 :(得分:1)
昨天我遇到了类似的问题并且主要解决了这个问题。我想在这里分享我的解决方案 首先,我们都知道它是所谓的CORS标准(跨源资源共享),这意味着我们从网站A开放的一个资源请求来自网站B的另一个资源(reference)。因此,在您的情况下,假设原始Web服务器(具有域AAA.com)和您的netty服务器(域BBB.com),然后将此行附加到您的netty服务器以获得权限:
config.setOrigin("http://AAA.com");
请注意,您无法在netty-socketio中为 Access-Control-Allow-Origin 使用通配符(*),因为它设置了凭据(即 Access-Control-Allow-Credentials )默认为TRUE(see here)。请记住,浏览器也会拒绝任何没有 Access-Control-Allow-Credentials:true 标头的响应,并且不会使响应可用于调用Web内容。希望这些帮助。
以下是我的图书馆版本:
netty-socketio版本
<dependency>
<groupId>com.corundumstudio.socketio</groupId>
<artifactId>netty-socketio</artifactId>
<version>1.7.6</version>
</dependency>
socket.io.javascript
script(type="text/javascript", src="https://cdn.socket.io/socket.io-1.3.5.js")
答案 1 :(得分:0)
使用netty-socketio 1.7.1或1.6.6版本。此版本中添加了通过Configuration.origin参数设置自定义Access-Control-Allow-Origin的功能。