Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node.js how to respond to an upgrade request?

I'm handling a websocket 'upgrade' event from a Node.js http server - The upgrade handler is in the form function(req, socket, head) - How can I send a response to this upgrade request given that there is no res object? Is there a way to do it using the socket object? How to send back headers?

like image 740
Jon Avatar asked Aug 04 '13 17:08

Jon


1 Answers

You just need to call socket.write with the appropriate HTTP syntax as plain text along these lines (from wikipedia):

HTTP/1.1 101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Accept: HSmrc0sMlYUkAGmm5OPpG2HaGWk=
Sec-WebSocket-Protocol: chat

Use \r\n line separators. After that point, HTTP is over and now you are just using the bare TCP socket.

like image 100
Peter Lyons Avatar answered Sep 28 '22 15:09

Peter Lyons