Reputation: 491
My server side code is as below:
var app = require('http').createServer(handler)
, io = require('socket.io').listen(app)
app.listen(1000);
function handler (req, res) {
function (err, data) {
res.writeHead(200);
res.end(data);
});
}
io.sockets.on('connection', function (socket) {
socket.emit('message', { hello: 'world' });
socket.on('my other event', function (data) {
console.log(data);
});
});
My browser side code is as below:
window.WebSocket = window.WebSocket || window.MozWebSocket;
if (!window.WebSocket){
alert("WebSocket not supported by this browser");
return;
}
var websocket = new WebSocket("ws://127.0.0.1:1000/");
websocket.onmessage = function(evt){
var data = evt.data;
console.log(data);
}
First I run server with 'node server.js', it's ok. And when I run the cient code,browser said it couldnt connect to '
' , why?
Do client side must write with socket.io too? http://127.0.0.1:1000
Upvotes: 0
Views: 1155
Reputation: 9126
You should connect to the server with socket.io client like this:
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io.connect('http://localhost:3000');
</script>
You might want to checkout my Scalable Socket.IO Sample.
Upvotes: 0
Reputation: 5048
yes you must talk with the right protocol to socket.io , look at socket.io-client and the examples in the documentation.
Upvotes: 1