Introduction to socket. io in node. js (2)

Source: Internet
Author: User
Tags emit
Socket. io provides event-based Real-time bidirectional communication. The following article mainly introduces socket. i/O basic application-related materials have some reference and learning value for everyone. Let's take a look at them. Socket. io provides event-based Real-time bidirectional communication. The following article mainly introduces socket. i/O basic application-related materials have some reference and learning value for everyone. Let's take a look at them.

Preface

Socket. IO supports timely, bidirectional, and event-based communication. It can work on every platform, every browser, and every device, with the same reliability and speed.

  • Real-time analysis: pushes data to clients, which are expressed as real-time counters, charts, or log customers.

  • Real-time communication and chat: only a few lines of code can be written into a Socket. IO "Hello, World" chat application.

  • Binary stream transmission: Starting from Version 1.0, Socket. IO supports binary file transmission in any form, such as images, videos, and audios.

  • Document merging: Allows multiple users to edit a document at the same time and view the modifications made by each user.

Connect the server to the client

Socket. io provides APIs for both the server and client.

The socket. io Server must be bound to an http. Server instance.

Bind http. Server

1. Implicit binding

Call the listen or attach function for implicit binding after passing in a port or instantiating during instantiation. Socket. io is instantiated and listened to internallyhttp.Server

Input Port during instantiation

let io = require('socket.io')(3000)

Bind directly through the listen or attach function. Listen and attach are synonymous

let io = require('socket.io') io.listen(3000) // io.attach(3000)

2. Display binding

You can manually specify http. Server

Bind during instantiation

let server = require('http').Server(); let io = require('socket.io')(server)server.listen(3000)

Bind through listen or attach

let server = require('http').Server(); let io = require('socket.io')()io.listen(server) // io.attach(server)server.listen(3000)

You can bind http frameworks such as express or koa.

Express

let app = require('express') let server = require('http').Server(app) let io = require('socket.io')(server)app.listen(3000)

Koa

let app = require('koa')() let server = require('http').Server(app.callback())let io = require('socket.io')(server)app.listen(3000)

Listener connection status

When the connection between the server and the client is successful, the server will listen to the connection and connect events (connection is synonymous with connect), and the client will listen to the connect event, when the connection is disconnected, both the socket and client corresponding to the client will listen to the disconnect event.

Server code

let server = require('http').Server() let io = require('socket.io')(server)server.listen(3000); io.on('connection', socket => {  console.log('connect') socket.on('disconnect', () => { console.log('disconnect') }) socket.disconnect()})

Print after running

connect disconnect

Client code

let socket = io('http://localhost:3000') socket.on('connect', () => {  console.log('connect')})socket.on('disconnect', () => {  console.log('disconnect')})

Print after running

connect disconnect

Transmit data

The socket of the server and the client is an associated EventEmitter object. Events distributed by the socket of the client can be received by the socket of the server, and events distributed by the socket of the server can also be accepted by the client. Based on this mechanism, two-way communication can be achieved.

Now we simulate a situation where the client continuously sends a random number. When the random number is greater than 0.95, the server sends a warning and warning message to the client after one second delay.

Server code

let server = require('http').Server() let io = require('socket.io')(server)server.listen(3000); io.on('connection', socket => {  socket.on('random', value => { console.log(value) if (value > 0.95) {  if (typeof socket.warning === 'undefined') socket.warning = 0  setTimeout(() => {  socket.emit('warn', ++socket.warning)  }, 1000) } })})

The socket object can be used to store status information and custom data, suchsocket.warning

Client code

let socket = io('http://localhost:3000') let interval = setInterval(() => {  socket.emit('random', Math.random())}, 500)socket.on('warn', count => {  console.log('warning count: ' + count)})socket.on('disconnect', () => {  clearInterval(interval)})

Transmission stream

Socket. io can process streams

Server code

io.on('connection', function (socket) {  let stream = ss.createStream() ss(socket).emit('script', stream) fs.createReadStream(__filename).pipe(stream)})

Client code

let socket = io('http://localhost:3000') ss(socket).on('script', stream => {  let buffer = ''  stream.on('data', data => { buffer += data.toString() }) stream.on('end', () => { console.log(buffer) })})

The above is the details of the socket. io tutorial in node. js (2). For more information, see other related articles in the first PHP community!

Related Article

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.