JS案例:Socket聊天室(两种方式)

一.socket轮询(每隔一段时间向后端请求一次,增加服务器压力):

由于socket连接时采用ws/wss协议,页面必须放在服务器端,所以首先用node产生一个静态文件夹,方便通过IP直接访问

static.js:

const express = require('express');//这里要引入express
const app = express();
const path = require('path');
app.use('/main', express.static(path.join(__dirname, './html')));//设置静态文件夹
app.listen(2048, () => {//端口号不能与socket监听的端口号一样
    console.log('static 2048 Server Start~');
})

在html界面做一些简单的布局以及socket数据请求:

index.html:





  
  
  
  Document
  



  

Client.js(客户端)

const WebSocket = require('ws');//这里引入一个模块ws

const ws = new WebSocket('ws://192.168.1.4:1024');//对1024端口进行监听
 
ws.on('open', function() {
  console.log('Client is listening on port 1024');
});
ws.on('message', function(msg) {
    ws.send(msg);//获取到前端传来的数据后,直接向服务端传递
});
ws.on('close',function(){ 
    console.log('Client close')
}); 

Server.js

const static = require('./static')//引入刚刚创建的static静态目录
const client = require('./client')//引入客户端
const WebSocket = require('ws');
let list = [];
const wss = new WebSocket.Server({//对1024端口进行监听
    port: 1024
}, () => {
    console.log('Server is listening on port 1024');
});

wss.on('connection', function (ws) {
    ws.on('message', function (msg) {//对数据过滤和处理
        if(!JSON.parse(msg).err){
            list.push(JSON.parse(msg).netName + ' 说: ' + JSON.parse(msg).msg)
        }
        ws.send(JSON.stringify(list));//将数据传到前端
    });
});

二.socketio长链接(与轮询不同,使前后端通过事件处理机制时刻保持连接状态)

同样产生一个静态文件夹:

static.js:

const express = require('express');
const app = express();
const path = require('path');
app.use('/main', express.static(path.join(__dirname, './static')));
app.listen(2048, () => {
    console.log('static 2048 Server Start~');
})

index.html





  
  
  
  Document
  
  
  



  

Server.js:

const static = require("./static");//引入刚刚创建的static静态目录
let list = [];//聊天记录缓存
var express = require("express");
var app = express();
var server = require("http").Server(app);
const io = require("socket.io")(server);
io.on("connection", function(client) {
  client.on("send", data => {//添加send监听事件
    list.push(data.netName + " 说: " + data.msg);//将前端事件传过来的参数进行处理
    sendList(list, client);//将数据通过事件发送到前端
  });
});
function sendList(list, target) {
  target.broadcast.emit("msg", list);//触发msg事件
}
server.listen(1024, "192.168.1.4", () => {
  console.log("Connect Success At 1024");
});

 

你可能感兴趣的:(JavaScript,Node.js)