socket.io API web端实时通信框架
1、介绍安装 创建服务器
socket.io 是一个为浏览器服务器端之间提供实时的,双向的,基于事件通信的一个网络通信库,实现websocket协议。
在客户端服务器创建一个新的文件夹socketserver,在该文件夹终端打开输入
npm install --save express
npm install --save socket.io
2、进入socketserver文件夹,创建index.js文件服务器
//index.js
//启动web服务,监听3000端口 绑定socket.io服务,接受websocket连接请求
const http = require('http').createServer();
const express = require('express')
// 创建web服务实例
const socketio = require('socket.io')(http,{
cors:{
origin:"http://127.0.0.1:5500",
methods:['GET','POST']
}
})
http.listen(3000,function(){
console.log('server is running...')
});
3、客户端建立连接发送消息
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>client.html</title>
<script src="./socket.io.js"></script>
</head>
<body>
<button id="conn">点我建立连接</button>
<button id="send">点我发消息</button>
</body>
<script>
let socket;
//send1发消息
let btn = document.getElementById('conn');
btn.addEventListener('click',()=>{
socket = io('ws://localhost:3000/');//连接服务器的端口
console.log(socket);
socket.on('textmsg',(data)=>{
alert(data)//成功后弹出服务端发来的消息
})
})
let send=document.getElementById('send');
send.addEventListener('click',()=>{
if(!socket){//判断是否连接上
alert('请先建立连接!');
return;
}
socket.emit('textmsg',"客户端发送消息");
})
</script>
</html>
4、服务器端接收客户端传来的消息,发送消息到客户端
socketio.on('connection',(socket)=>{
console.log('客户端连接:'+socket.id)
socket.on('textmsg',(data)=>{
console.log(socket.id+':'+data)
socket.emit('textmsg','瞅你咋地?找抽?')
})
})
http.listen(3000,function(){
console.log('server is running...')
});