介绍:
使用流行的Web应用程序堆栈(如LAMP(PHP))编写聊天应用程序一直非常困难。它涉及轮询服务器以进行更改,跟踪时间戳,并且它比它应该慢得多。
套接字传统上是大多数实时聊天系统所围绕的解决方案,在客户端和服务器之间提供双向通信通道。
这意味着服务器可以将消息推送到客户端。每当您编写聊天消息时,其想法是服务器将获取它并将其推送到所有其他连接的客户端
确定下载了node
使用Node.JS Web框架express
npm i --save express@4.15.2
let app=require('express') ();
let http=require('http').Server(app);
app.get('/',(req,res)=>{
res.send('<h1>hello word</h1>')
})
http.listen(3000,()=>{
console.log('success')
})
启动
还可以用res.sendFile(__ dirname + '/ index.html');启动html文件
集成Socket.IO
socket.io
我们会自动为客户服务,所以现在我们只需要安装一个模块:
npm install --save socket.io
|
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('listen on *:3000'); }); |
io.emit 发出事件
io.emit('某事件',{ for:'everyone' });
|
除了某个套接字以外的所有人发送消息,我们有以下broadcast标志
io.on('connection',function(socket) {
socket.broadcast.emit('hi');
});
将消息发送给所有人,包括发件人。
io.on('connection',function(socket) {
socket.on('chat message',function(msg) {
io.emit('chat message',msg);
});
});