Created
January 26, 2018 08:01
-
-
Save jarvisniu/fb5d53d53b0cf0751af45ac8a361785e to your computer and use it in GitHub Desktop.
socket.io 2.0 demo
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| var socket = require('socket.io-client')('http://localhost:3000'); | |
| socket.on('connect', function(){ | |
| console.log('Connection success!') | |
| }); | |
| socket.on('event', function(data){ | |
| console.log('Recieved data: ', data) | |
| }); | |
| socket.on('disconnect', function(data){ | |
| console.log('Connection closed, resean: ', data) | |
| }); | |
| setTimeout(function (){ | |
| console.log('sending') | |
| socket.emit('msg', {name: 'Jarvis', age: 12}) | |
| }) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| var server = require('http').createServer(); | |
| var io = require('socket.io')(server); | |
| // 连接时,创建一个client对象 | |
| io.on('connection', function(client){ | |
| // client is a Socket object | |
| console.log('a user connected, id = ', client.conn.id) | |
| // 客户端发来数据时,产生event事件 | |
| client.on('msg', function(data){ | |
| console.log('on event msg', data) | |
| }); | |
| client.on('disconnect', function(data){ | |
| console.log('client disconnect', data) | |
| }); | |
| }); | |
| server.listen(3000); |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
npm i socket.io socket.io-client