Socket polling (request to the back end once in a while, increase server pressure) :
Since the WS/WSS protocol is used for socket connection, the page must be placed on the server side, so first use Node to generate a static folder, which is convenient for direct access through IP
static.js:
const express = require('express');// We want to introduce express
const app = express();
const path = require('path');
app.use('/main', express.static(path.join(__dirname, './html')));// Set the static folder
app.listen(2048.() = > {// The port number cannot be the same as the port number monitored by the socket
console.log('static 2048 Server Start~');
})
Copy the code
Do some simple layout and socket data request in HTML interface:
Index.html:
<! DOCTYPEhtml>
<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>Document</title>
<style>
#text {
width: 350px;
height: 30px;
}
#netName {
width: 150px;
height: 30px;
}
</style>
</head>
<body>
<textarea name="" id="msg" cols="80" rows="30" readonly></textarea><br />
<input id="netName" type="text" placeholder="Name" />
<input id="text" type="text" placeholder="News" />
<button onclick="clickHandler()">send</button>
<script>
setInterval(sendMsg, 1000); // do the polling request here
function sendMsg(data) { // Encapsulate the WebSocket request function
if(! data) { data = {err: 1
}; // Check whether the parameters are consistent with the data specification
}
var ws = new WebSocket(Ws: / / 192.168.1.4:1024 ""); // Use the WS protocol to request port 1024
ws.onopen = function () {
ws.send(JSON.stringify(data));
};
ws.onmessage = getData;
}
function getData(evt) { // Receive the data returned after a successful request
var received_msg = evt.data;
var val = JSON.parse(evt.data).join("\n");
msg.value = val;
}
document.addEventListener("keyup".e= > { // Enter to send
if(e.keyCode ! = =13) return;
clickHandler(e);
});
function clickHandler() { // Send data to server when Button is clicked
if (netName.value.trim().length == 0 || text.value.trim().length == 0)
return;
var obj = {
err: 0.netName: netName.value,
msg: text.value
};
sendMsg(obj);
text.value = ""; // Empty the content after each send
}
</script>
</body>
</html>
Copy the code
Client.js (Client)
const WebSocket = require('ws');// Introduce a module ws here
const ws = new WebSocket('ws: / / 192.168.1.4:1024');// Listen on port 1024
ws.on('open'.function() {
console.log('Client is listening on port 1024');
});
ws.on('message'.function(msg) {
ws.send(msg);// Get the data from the front end and pass it directly to the server
});
ws.on('close'.function(){
console.log('Client close')});Copy the code
Server.js
const static = require('./static')// Import the static directory you just created
const client = require('./client')// Import the client
const WebSocket = require('ws');
let list = [];
const wss = new WebSocket.Server({// Listen on port 1024
port: 1024
}, () = > {
console.log('Server is listening on port 1024');
});
wss.on('connection'.function (ws) {
ws.on('message'.function (msg) {// Filter and process data
if(!JSON.parse(msg).err){
list.push(JSON.parse(msg).netName + 'said:' + JSON.parse(msg).msg)
}
ws.send(JSON.stringify(list));// Pass the data to the front-end
});
});
Copy the code
2. Socketio long links (unlike polling, so that the front and back ends are always connected through event handling mechanisms)
Also generates a static folder:
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~');
})
Copy the code
index.html
<! DOCTYPEhtml>
<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>Document</title>
<style>
#text {
width: 350px;
height: 30px;
}
#netName {
width: 150px;
height: 30px;
}
</style>
<script src="./socket.io.js"></script>
<! Socket. IO -client socket. IO -client socket.
</head>
<body>
<textarea name="" id="msg" cols="80" rows="30" readonly></textarea><br />
<input id="netName" type="text" placeholder="Name" />
<input id="text" type="text" placeholder="News" />
<button onclick="clickHandler()">send</button>
<script>
var socket = io.connect('http://192.168.1.4:1024'); // Establish an HTTP connection
var list = [] // Local chat record cache
function clickHandler() {
if (netName.value.trim().length == 0 || text.value.trim().length == 0)
return; // Filter the input box
var obj = {
netName: netName.value,
msg: text.value
};
list.push(obj.netName + 'said:' + obj.msg)
socket.emit('send', obj)// Send events are triggered
getData(list);
text.value = "";
}
socket.on('msg'.function (msg) {// Add MSG listening events
list = msg;
getData(list)
})
function getData(arr) {// Place the chat record in the area tag
msg.value = arr.join('\n');
}
</script>
</body>
</html>
Copy the code
Server.js:
const static = require("./static");// Import the static directory you just created
let list = [];// Cache chat records
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= > {// Add send listening events
list.push(data.netName + " 说: " + data.msg);// Process the parameters passed by the front-end event
sendList(list, client);// Send data to the front end via events
});
});
function sendList(list, target) {
target.broadcast.emit("msg", list);// Trigger the MSG event
}
server.listen(1024."192.168.1.4".() = > {
console.log("Connect Success At 1024");
});
Copy the code