Node.js and web-socket-js simple client server not opening
My 开发者_开发问答server.js seems to be correct..
var http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello World\n');
}).listen(1337, "mysite.com");
console.log('Server running at mysite.com:1337/');
The meat of my client is below.
function init() {
// Connect to Web Socket.
// Change host/port here to your own Web Socket server.
ws = new WebSocket("ws://mysite.com:1337");
// Set event handlers.
ws.onopen = function() {
output("onopen");
};
}
If I go to http://www.mysite.com:1337 I correctly receive Hello World! However, when I try to connect using my client, and debug in Fire bug, I get the following output.
[WebSocket] connected
[WebSocket] request header: GET / HTTP/1.1 Upgrade: WebSocket Connection: Upgrade Host: mysite.com:1337 Origin: http://www.mysite.com Cookie: Sec-WebSocket-Key1: 115 17 p^!x-93 IERc16 7 Sec-WebSocket-Key2: 1 75 7Z i `. 8u $l031 4j9
[WebSocket] sent key3: ±Ôñ<g
[WebSocket] closed
And the WebSocket is automatically closed before I have any chance to do anything. Can anyone please shed some light on the error I am receiving and what do you think I should do?
You have created a node.js HTTP server but you are trying to connect to it as a WebSockets server. The WebSockets protocol is not plain sockets and it is not plain HTTP request. WebSockets have an HTTP like handshake but after that you have a full-duplex connection (like sockets and unlike HTTP) that has a small amount of message framing (unlike plain sockets).
Try using Socket.IO or node-websocket-server if you want to create a node.js WebSockets server. On the other hand if you are wanting to connect from Javascript to a regular HTTP server then use one of the great Javascript libraries with AJAX support such as jQuery.
精彩评论