Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
294 views
in Technique[技术] by (71.8m points)

javascript - Socket.io + PhoneGap

When I try to use Socket.IO with PhoneGap I get this error:

(on iOS where socket.io should be supported)

Origin null is not allowed by Access-Control-Allow-Origin.

This is because my app is served via file:// protocol. What can I do to get around this?

Thanks!!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You have to add the socketio host to the "ExternalHosts" key in PhoneGap.plist.

See Faq:

Q. Links to and imported files from external hosts don't load?

A. The latest code has the new white-list feature. If you are referencing external hosts, you will have to add the host in PhoneGap.plist under the "ExternalHosts" key. Wildcards are ok. So if you are connecting to "http://phonegap.com", you have to add "phonegap.com" to the list (or use the wildcard "*.phonegap.com" which will match subdomains as well). (Note: If you open the plist file in Xcode, you won't need to fiddle with the XML syntax.)

For android you have to edit cordova.xml and add access to the socketio host:

<access origin="HOST*"/> 

index.html (with socketio example):

...
<script src="HOST/socket.io/socket.io.js"></script>
<script>
    var socket = io.connect('HOST');
    socket.on('news', function (data) {
        socket.emit('my other event', { my: 'data' });
    });
</script>
...

app.js (server side javascript / basic socketio example):

var io = require('socket.io').listen(80);

io.sockets.on('connection', function (socket) {

socket.emit('news', { hello: 'world' });
    socket.on('my other event', function (data) {
        console.log(data);
    });
});

The HOST you have to replace with hostname of your socket.io server!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...