前段通信
node 中的net 模块提供的前段通信
const net = require('net')//引入net模块,用来创建服务器
const server = net.createServer()//创建服务器
const port = 8000
const host = '10.31.158.47'
const count = 0//用于给客户端起一个名字,以至于不会让客户端不知道谁是谁
const clients = {}//创建一个对象将所有的客户端存放在这
server.on('connetion',client=>{//与客户端连接,用connection来连接
client.name = ++count//客户端的数量
clients[client.name] = client//将客户端存放入对象中
client.on('data',msg=>{//接收客户端发来的信息
console.log(`客户端${client.name}说:${msg}`)
boradCaster(client,msg)
})
client.on('error',error=>{
console.log(`error:${error}`)
})
client.on('close',()=>{
delete clients[client.name]
console.log(`客户端${client.name}下线`)
})
})
server.listen(port,host,()=>{
console.log(`服务器运行在:http:${host}:${port}`)
})
//定义一个广播函数,用来接收所有每一个客户端发来的信息,输出在服务器上
function boradCaster(clinet,msg){
for(var key in clients){
clients[key].write(`客户端${clinet.name}说:${msg}`)
}
}
const net = require('net')
const socket = net.Socket()
const readline = require('readline')
socket.connect(post,host,()=>{//连接服务器,并将信息发送给服务器,port和host的地址必须和服 务器地址相同
socket.write('我上线了')
say()
})
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
socket.on('error',error=>{
console.log(`error:${error}`)
})
scoket,on('close',()=>{
console.log(`我下线了`)
})
//定义一个函数,来发送每一个客户端的信息
function boradCaster(){
rl.question('请输入:', ( answer ) => {
if( answer === 'bye' ){
//表示正常下线
socket.destroy() // 客户端销毁
rl.end() // rl 读取命令行关闭
}else{
//表示正常聊天
socket.write( answer )
}
});
}
H5提供的 webSocket 【 常用于 移动端 】
//创建通信服务器
const Websocket = require('ws')
const ws = new Websocket.Server({//创建通信服务器的地址
port:8000,
host:10.31.158.47
})
let count = 0
const clients = {}
ws.on('connection',client=>{
client.name = ++count
clients[client.name]=client
client.on('message',msg=>{
console.log( `客户端${ client.name }说:${ msg }` )
boardCaster(client,msg)
})
client.on('error',error=>{
console.log(`error:${error}`)
})
client.on('close',()=>{
delete clients[client.name]
console.log(`客户端${client.name}下线了`)
})
})
//广播函数
function boardCaster ( client,msg ) {
// 这里是用的send方法
for( var key in clients ) {
clients[ key ].send( `客户端${ client.name }说: ${ msg }` )
}
- 第二步在同一个目录下建立一个client文件夹,在该文件夹下建立一个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>WebSocket</title>
</head>
<body>
<h1> 聊天室 </h1>
<div id="content" name="name" style="overflow-y: scroll; width: 400px; height: 300px; border: solid 1px #000"></div>
<br />
<div>
<input type="text" id="msg" style="width: 200px;">
</div>
<button id="submit">提交</button>
<script src="WsClient.js" charset="utf-8"></script>
<script>
var submit = document.querySelector('#submit')
var msg = document.querySelector('#msg')
submit.onclick = function () {
ws.send( msg.value ) //将信息发送通信服务器
msg.value = ''
}
</script>
</body>
</html>
- 然后写聊天室的结构
- 再建立一个app.ja(静态服务器)是与client文件夹同级的
//要引用两个第三方模块express和path
const express = require( 'express' )
const port = 8000
const host = '10.31.158.47'
const path = require( 'path' )
const app = express()// app对象的创建是为了绑定中间件
// 理解: 为了调用中间件( 函数 )
// 指定静态资源目录
/*
问题: 如果不指定静态资源目录,那么express启动的服务器就认为
/client/index.html 是一个路由
解决: 指定静态资源目录
*/
// console.log( __dirname ) // 当前文件所在的磁盘路径
app.use(express.statc(path,join(__dirname,'client')))
app.listen( port,host,() => {
console.log( `服务器运行在: http://${ host }:${ port }` )
})
- 第三步在client文件夹里建立一个js文件,用来连接通信服务器
const url = 'ws://10.31.158.47:5000'
const ws = new WebSocket( url )
ws.onopen = () => { //初次连接
ws.send('我进入了xxx的直播间')
}
ws.onmessage = msg => {
var content = document.querySelector('#content')
console.log( msg )
content.innerHTML += msg.data + '<br/>'
express
const express = require('express')//引入express
const app = express()//绑定中间件
const port = 8090
const host = 'localhost'
const fs = require('fs')//引入fs模块
app.get('/home',(req,res,next)=>{
//res:与前端有关,是用来接收后端返回的数据
//req:与后端有关,是用来接收前端发送的数据
//名词解释:
//1. req: request 请求 出发地: 杭州
//2. res: response 响应 目的地: 上海
//3. next: 表示request到response的一个过程 路程
//next决定了请求和响应之间的连通
//req.query 接收前端发来的get请求携带的数据
res.json{//接口的数据,检验接口数据的软件:insomnia
name:panda-pan,
sex:'男'
}
//创建一个data。txt
fs.writeFlie('./data.txt',JSON.stringify(req.query),()=>{//req.query返回后端的接口数据
console.log('存储成功')
})
})
app.listen( port,host, () => {
console.log( `express搭建的服务器运行在:http://${ host }:${ port }` )
})