nodejs+express+socket.io

其實官網文檔清楚了  https://socket.io/get-started/chat/html

可是由於以前寫的是nodejs+express, socket.io是後加的, 仍是有小坑node

服務器端:

官網代碼git

var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);

app.get('/', function(req, res){
  res.sendFile(__dirname + '/index.html');
});

io.on('connection', function(socket){
  console.log('a user connected');
});

http.listen(3000, function(){
  console.log('listening on *:3000');
});

注意這裏是http.listen而不是app.listen!github

若是是app.listen  客戶端會打開web頁面,  但一直報連不上socket.io 404 not foundweb

 

2 注意它用的是 app.get('/')express

也能夠直接用1行static服務器

// app.get("/", (req, res) => res.send("Hello World!"));

app.use(express.static(config['PATH_OVERLAY_STATIC']))

但必須註釋掉app.get('/')app

 

客戶端:

必須用socket.io-client不然會報錯.socket

注意官網和github用法不一樣ui

https://socket.io/get-started/chat/

 

io.on('connection', function(socket){
  socket.on('chat message', function(msg){
    console.log('message: ' + msg);
  });
});

github https://github.com/socketio/socket.io-client

<script src="/socket.io/socket.io.js"></script>
<script>
  var socket = io('http://localhost');
  socket.on('connect', function(){});
  socket.on('event', function(data){});
  socket.on('disconnect', function(){});
</script>

// with ES6 import


import io from 'socket.io-client';

const socket = io('http://localhost');

區別是io 彷佛再也不提供io.on 這樣的connect 事件了, 直接只使用

socket.on('connect', function(){});

 

可是如今socket.io-client基本沒什麼更新了. 先按github的方法用把. 

相關文章
相關標籤/搜索
本站公眾號
   歡迎關注本站公眾號,獲取更多信息