介绍
Socket.IO 是一个库,可以在浏览器和服务器之间实现实时、双向和基于事件的通信。 Socket.IO不是WebSocket 实现。尽管 Socket.IO 确实在可能的情况下使用 WebSocket 作为传输,但它为每个数据包添加了额外的元数据。这就是为什么 WebSocket 客户端将无法成功连接到 Socket.IO 服务器,而 Socket.IO 客户端也无法连接到普通 WebSocket 服务器的原因。
HTTP长轮询
HTTP 长轮询传输(也简称为“轮询”)由连续的 HTTP 请求组成:
- 长时间运行的
GET
请求,用于从服务器接收数据 - 短期
POST
请求,用于向服务器发送数据 由于传输的性质,连续的发射可能会在同一个 HTTP 请求中连接和发送。
index.js
var socket=io('http://localhost:6060')
$('#send').click(()=>{
socket.emit('fasong',$('#message').val())
$('#message').val('')
})
//发送消息的方法
function send(){
socket.emit('message',$(''))
}
socket.on('gongping',function(data){
$('#top').append(`<div class=row>${data}</div>`)
})
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
*{
margin: 0;
padding: 0;
}
#talkbox{
width: 400px;
height: 500px;
margin:50px auto;
position: relative;
border:1px solid #ccc;
display:none
}
#top{
position: absolute;
top:20px;
left:20px;
right:20px;
bottom:80px;
overflow:auto;
}
#bottom{
position: absolute;
bottom:20px;
right:20px;
left:20px;
overflow: hidden;
}
#message{
width: 300px;
height: 30px;
float: left;
line-height: 30px;
box-sizing: border-box;
}
#send{
width: 55px;
float: right;
height: 30px;
line-height: 30px;
}
.row{
line-height: 35px;
}
</style>
</head>
<body>
<div id="talkbox" >
<div id="top"></div>
<div id="bottom">
<input type="text" id="message">
<input type="button" value="发送" id="send">
</div>
</div>
<script src="./jquery.js"></script>
<script src="./socket.io.js"></script>
<script src="./index.js"></script>
</body>
</html>
app.js
const express=require('express')
const path=require('path')
const app=express();
// const jwt=require('jsonwebtoken')
app.use(express.static(path.join(__dirname,'public')))
const server=require('http').createServer(app)
const io=require('socket.io')(server)
// app.use('*',function(req,res,next){
// })
//登录
app.get('/login',(req,res,next)=>{
let token=jwt.sign({
username:req.query
},'asdf');
res.send({token})
})
var userID=0
io.on('connection',function(socket){
userID++;
socket.on('fasong',function(text){
io.emit('mgongping',userID+'-----:'+text)
})
io.emit('gongping',userID+'上线了')
socket.on('disconnect',function(){
io.emit('gongping',userID+'下线了')
// console.log(1)
})
})
// // ☆ 这里要用server去监听端口,而非app.listen去监听(不然找不到socket.io.js文件)
server.listen(6060,()=>{
console.log('http://localhost:6060')
})