Reputation: 5409
I am using Node.js with socket.io to implement websockets in one of my pages. server.js (what Node.js runs) has this code:
var http = require("http").createServer(),
io = require("socket.io").listen(http);
http.listen(8080);
io.sockets.on("connection", function(socket) {
socket.emit("message", {hello:"world"});
});
And this is the code I'm trying to connect with:
var socket = new WebSocket("ws://92.60.122.235:8080/");
socket.onopen = function() {
alert("Socket has been opened!");
}
When I load the page, nothing happens. I'm using Chrome, and I know websockets are supported. No errors are present in the error console, and if I watch socket.io serving requests from command line I don't see any user connecting.
As far as I know this should work, could anyone explain what could be going wrong?
Upvotes: 1
Views: 4595
Reputation: 1971
You can download the webpage source code that runs in Chrome, Firefox, and IE (at least) via the blog article "Websocket Server Demonstration" from the High Level Logic Project. The webpage is set up for developers.
Upvotes: 0
Reputation: 30430
You need a socket.io client to pass some authentication phases I believe. Try this, and it should work(the client javascript is served by socket.io itself, don't worry about it).
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io.connect('http://localhost');
socket.on('message', function (data) {
console.log(data);
socket.emit('helloworld', { msg: 'why do you so love to say hello world?' });
});
</script>
Why not just call it
WebSocket
if the actual WebSocket is not present and mimick its API?Socket.IO does more than WebSocket, even if WebSocket is selected as the transport and the user is browsing your website with an ultra modern browser. Certain features like heartbeats, timeouts and disconnection support are vital to realtime applications but are not provided by the WebSocket API out of the box.
This is akin to jQuery's decision of creating a feature-rich and simple $.ajax API as opposed to normalizing XMLHttpRequest.
Upvotes: 7