socket.io学习记录

基础看这里 WebSocket 教程

https://socket.io/docs/
https://segmentfault.com/a/11...
用Socket.io打造协作应用

Installing

$ npm install socket.io

Using with Node http server

Server (app.js)

var app = require('http').createServer(handler)
var io = require('socket.io')(app);
var fs = require('fs');

app.listen(80);

function handler (req, res) {
  fs.readFile(__dirname + '/index.html',
  function (err, data) {
    if (err) {
      res.writeHead(500);
      return res.end('Error loading index.html');
    }

    res.writeHead(200);
    res.end(data);
  });
}

io.on('connection', function (socket) {
  socket.emit('news', { hello: 'world' });
  socket.on('my other event', function (data) {
    console.log(data);
  });
});
  

Client (index.html)




开始练习

实例1 https://segmentfault.com/a/1190000004925844



  
    Socket.IO chat
    
  
  
    
    var app = require('express')();
    var http = require('http').Server(app);
    var io = require('socket.io')(http);
    var port = process.env.PORT || 3000;
    
    app.get('/', function(req, res){
      res.sendFile(__dirname + '/index.html');
    });
    
    io.on('connection', function(socket){
      socket.on('chat message', function(msg){
        io.emit('chat message', msg);
      });
    });
    
    http.listen(port, function(){
      console.log('listening on *:' + port);
    });

    Getting this example

    You can find it on GitHub here.

    $ git clone https://github.com/socketio/chat-example.git 
    

    常见问题

    socket.broadcast calling itself also #3165

    原理分析

    socket.io 原理分析

    你可能感兴趣的:(node.js,socket.io)