以前客户端和服务器维持通信使用轮训、长轮训之类的,消耗资源,现在浏览器原生支持websocket,就是你了骚年。给毕设的作品加一个消息模块,学下用下。
在node中建立连接试试
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| var server = require('ws').Server; var wss = new server({ port:8080 }) wss.on('connection',function(ws){ ws.on('message',function(msg){ console.log('receive from client:'+msg); ws.send('hi client'); }) }) var websocket = require('ws'); var ws = new websocket('ws://localhost:8080'); ws.on('open',function(){ ws.send('hi server'); }) ws.on('message',function(msg){ console.log('from server'+msg); })
|
浏览器中
事件上的差别 大体相同
1 2 3 4 5 6 7 8 9
| <script> var socket=new WebSocket('ws://localhost:8080/'); socket.onopen = function () { socket.send('hi'); } socket.onmessage = function (ev) { console.log(ev.data); } </script>
|
socket.io
适配不同环境不同浏览器,有优雅的降级方案(websocket是h5的新特性 老浏览器不支持)
客户端上引入socket.io文件,路径是写死的,这个js文件是内存里自动生成的(原理是服务器端能监听这个路由去读相应的文件)
这边的 io
对象就像angular一样,我们运行socket.io.js的时候,就会在window对象下挂一个io对象
1 2 3 4 5 6 7 8 9 10 11 12 13
| <script src="/socket.io/socket.io.js"></script> <script> window.onload = function () { var socket = io.connect('ws://localhost:8004'); socket.on('connect',function () { console.log('conected') }) socket.on('message',function (msg) { console.log(msg) }) } </script>
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| var express = require('express'); var http = require('http'); var path = require('path'); var app = express(); app.get('/',function(req,res){ res.sendFile(path.join(__dirname,'index.html')); }) var server = http.creatServer(app); var io = require('socket.io')(server); io.on('connection',function(socket){ socket.on('message',function(msg){ socket.send(msg) }) })
|
###