Nodejs Socket.io Module--WebSocket protocol implemented

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.