Nodejs implementation of the WebSocket 4 ways: Socket.io, Websocket-node, Faye-websocket-node, Node-websocket-server, the main use of this is Socket.io
1, the service side:
1) First install the Socket.io
NPM Install Socket.io
2) Server.js
var app = require (' http '). Createserver (handler), IO = require (' Socket.io '). Listen (APP), fs = require (' FS ') App.listen (8080); Io.set (' Log level ', 1);//Turn the debug information in Socket.io off function handler (req, res) { Fs.readfile (__ DirName + '/index.html ', function (err, data) { if (err) { res.writehead ($); Return Res.end (' Error loading index.html '); } Res.writehead ($, {' Content-type ': ' text/html '}); Res.end (data); });} Io.sockets.on (' Connection ', function (socket) { socket.emit (' news ', {hello: ' world '}); Socket.on (' My other event ', function (data) { console.log (data); });});
2. Client:
1) WebSocket is the HTML5 standard, the browser has been supported, its programming interface roughly connect, close, open, send several interfaces, if you want to use the browser native way to write websocket, more cumbersome, So you can download a client library for easy programming, using the Socket.io client library, click the Open link
2) index.html
<! DOCTYPE html>
3. Test:Start Server Nodejs Code: node Server.js
In the browser input http://localhost:8080/index.html
Browser Print out: World
Command line print out: {my: ' Data '}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Nodejs Socket.io Module-implements the WebSocket protocol