前端通信
- 基于后端的通信( 后端完成 )( pc端用 )
- Node.js中有一个net模块
- 使用终端( shell )作为客户端
- 思维流程
/*
主服务器:
1.创建服务器
2.连接客户端
3.获取客户端发来的信息
4.将客户端发来的信息展示到自己的终端上(广播)
*/
// 引入net模块
const net = require('net');
// 1.创建服务器
const server = new net.createServer();
const port = 8000;
const hostname = 'localhost';
const clients = {}; //用来存储多个客户端
let count = 0; // 用来给客户端编号的
// 2.连接客户端
server.on('connection', client => { //client指的是连接的客户端
client.name = ++count;
clients[client.name] = client;
// 3.获取客户端发来的信息
client.on('data', msg => {
console.log(`客户端${client.name}说:${msg.toString()}`);
boardcast(client, msg.toString())
});
client.on('error', error => {
console.log(`error is ${error}`)
});
client.on('close', () => {
delete clients[client.name];
console.log(`客户端${client.name} closed~~`)
})
});
// 4.将客户端发来的信息展示到自己的终端上(广播)
// 封装一个广播函数用于广播客户端发来的消息
function boardcast(client, msg) { // client为客户端 msg为客户端发来的消息
// 把所有客户端发送来的消息都展示在聊天室内
for (var key in clients) {
clients[key].write(msg); // 将每一个客户端的消息都写入界面
}
}
// 监听服务器
server.listen(port, hostname, () => {
console.log(`The server is running at: http://${hostname}:${port}`)
});
/*
客户端:
1.创建socket;
2.通过socket连接服务器;
3.给服务器发送信息
*/
// 1.创建socket;
const net = require('net');
const socket = new net.Socket();
const port = 8000;
const hostname = 'localhost';
const readline = require('readline'); // 用作命令行的逐行读取
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
// 2.通过socket连接服务器;
socket.connect(port, hostname, () => {
socket.write(`欢迎xxx来到xxx的直播间`);
socket.on('error', error => {
console.log(`socket error is ${error}`)
});
socket.on('close', () => {
console.log(`socket connection closed~~`)
})
// 3.给服务器发送信息
socket.on('data', msg => {
console.log(msg.toString()); //客户端显示自己写的内容
say();
})
function say() {
rl.question('请输入:', (answer) => { //answer就是客户端输入的内容
if (answer === 'bye') {
socket.destroy(); //消除命令行的连接
rl.close(); //关闭命令行读取
} else {
socket.write(answer);
}
});
}
})
- 基于H5的webSocket来完成( 应用于移动端 )
/*
主服务器:
1.通过ws模块创建服务器
2.连接客户端
3.接收客户端发来的消息
4.监听客户端下线
5.将客户端发来的消息广播在界面上
*/
// 1.通过ws模块创建服务器
// 在根目录下创建package.json文件 npm init -y
// 安装第三方模块 ws npm i ws -S
// 引入ws模块
const webSocket = require('ws');
// 通过ws模块来创建服务器
const ws = new webSocket.Server({
port: 7000,
host: 'localhost'
})
// 把所有客户端放在一个对象里
const clients = {};
// 给每个客户端进行编号
let count = 0;
// 2.连接客户端
ws.on('connection', client => {
client.name = ++count;
clients[client.name] = client;
// 3.接收客户端发来的消息
client.on('message', msg => {
console.log(`客户端${client.name} 说:${msg}`); // h5中不需要转二进制
boardcast(client, msg);
});
// 4.监听客户端下线
client.on('close', () => {
// 删除客户端
delete clients[client.name];
console.log(`客户端${client.name} is closed~~`)
})
})
// 将客户端发来的消息广播在界面上
function boardcast(client, msg) { // client为客户端 msg为客户端发来的消息
// 遍历客户端 将客户端放到界面上
for (var key in clients) {
// 将每个客户端发送的消息写到界面上
clients[key].send(msg); // h5为send方法
}
}
/*
客户端连接服务器文件
h5 提供了一个 Socket 的全局对象
*/
const ws = new WebSocket('ws://10.31.161.69:8000')
ws.onopen = () => {
ws.send('欢迎来到xxx的直播间')
}
ws.onmessage = (msg) => {
const content = document.querySelector('#content');
content.innerHTML += msg.data + '<br/>'
}
ws.onerror = (error) => {
if (error) {
console.log(error)
}
}
ws.onclose = () => {
console.log(`xxx下线了`)
}
写前端页面聊天室内容
<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>
/*
1. 获取数据 发ajax
2. 获取dom jq / css3
3. 渲染数据 jq字符串拼接
4. 添加事件 jq on
*/
var msg = document.querySelector('#msg');
var submit = document.querySelector('#submit');
submit.onclick = function() {
var val = msg.value;
ws.send(val)
msg.value = ''
}
</script>
</body>
</html>
创建一个静态服务器展示客户端信息,链接前端聊天室页面
/*
这个静态服务器是为了展示客户端界面的
*/
const express = require('express');
const app = express();
const port = 4000;
const hostname = '10.31.161.69';
const path = require('path');
console.log(path.join(__dirname, 'client'));
// 我们需要设置一个静态文件夹 让我们的服务器找到client/index.html
app.use(express.static(path.join(__dirname, 'client')))
app.listen(port, hostname, () => {
console.log(`The web Server is running at: http://${ hostname }:${ port }`)
})