socket可以实现用户交互: 用emit发送出去 再由broadcast.emit广播出去 在另一边用socket.on监听接受发送出来的变量
安装
1
| npm install socket.io --save
|
在app.js中的配置
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
| const app = require("express")(); const http = require("http").Server(app); const io = require("socket.io")(http)
app.get("/",function (req,res) { res.sendfile(__dirname+"/drag.html") })
io.on("connection",function(socket){ console.log('socket与服务器产生了链接') socket.on("disconnect",function(){ console.log("与服务器时区链接") })
socket.on("drag",function(data){ console.log(data) socket.broadcast.emit("drag",data) }) }) http.listen(3000,function(argument){ console.log("服务器创建成功了"); })
|
在页面用socket.on来监听广播回来的变量 来接受数据
1 2 3 4 5 6
| socket.on("welcome", function(data) { $("ul").append("" + data + "") socket.on("ReturnMsg", function(data) { $("ul").append("" + "大哥: " + data + "") }) })
|