一、Socket.io是什么
是基于时间的实时双向通讯库
基于websocket协议的
前后端通过时间进行双向通讯
配合express快速开发实时应用
二、Socket.io和ajax区别
基于不同的网络协议
ajax基于http协议,单向,实时获取数据只能轮询
socket.io基于websocket双向通讯协议,后端可以主动推送数据
现代浏览器均支持websocket协议(不必担心兼容问题)
如何安装socket.io
npm install socket.io --save (后端)
npm install socket.io-client --save(前端)
配合express(后端API)(只是顺带说一下不详解)
*io=require('socket.io')(http)
*io.on 监听事件
*io.emit触发事件
如下代码
.....const app = express()// work with expressconst server = require('http').Server(app)const io = require('socket.io')(server)io.on('connection',function(socket){ console.log('user login') socket.on('sendmsg',function(data){ //*************接收 console.log(data) const { from, to, msg} = data const chatid = [from,to].sort().join('_') Chat.create({chatid,from,to,content:msg},function(err,doc){ io.emit('recvmsg', Object.assign({},doc._doc)) //发送到全局 }) // console.log(data) // io.emit('recvmsg',data) })})....server.listen(9093,function(){ console.log('Node app start at port 9093')})
配合express(前端API)
*Import io from 'socket.io-client'
*io.on 监听事件
*io.emit 触发事件
前端发送消息
import React from 'react'import {List,InputItem,NavBar,Icon, Grid} from 'antd-mobile'import io from 'socket.io-client'const socket = io('ws://localhost:9093') class Chat extends React.Component{ constructor(props){ super(props) this.state={text:''} } componentDidMount(){ socket.on('recvmsg',(data)=>{ this.setState({ msg:[...this.state.msg,data.text] }) }) } handleSubmit(){ socket.emit('sendmsg',{text:this.state.text}) this.setState({text:''}) } render(){{ this.state.msg.map(v=>{ return) }}export default Chat{v}
}) }
{ this.setState({text:v}) }} extra={ this.handleSubmit()}>发送} > 信息