Native socket service
step
- create a new folder
- Create three files (dependencies)
expressSocketSever.js
package-lock.json
package.json
3. Open the editor terminal and execute npm i (or yarn i ), provided that there is a package manager npm or yarn
client
<!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>Document</title>
</head>
<body>
<input type="text" id="text">
<button id="btn" type="button">发送</button>
<script type="text/javascript">
const ws = new WebSocket('ws://localhost:8080')
// ws.onopen = function (e) {
// ws.send('来自客户端的信息')
// }
// ws.onmessage = function (e) {
// console.log(e.data);
// }
ws.onopen = function () {
document.getElementById('btn').onclick = function () {
ws.send(document.getElementById('text').value);
}
}
ws.onmessage = function (e) {
// document.body.innerHTML += `<p>${e.data}</p>`
let p = document.createElement('p')
p.innerHTML = e.data;
// appendChild() 方法可向节点的子节点列表的末尾添加新的子节点
document.body.appendChild(p);
}
</script>
</body>
</html>
Server
const ws = require('nodejs-websocket');
const POST = 8080;
//消息广播
let connections = [];
function broadcast(connections, msg) {
connections.forEach(function(conn){
conn.sendText(msg)})
}
const server = ws.createServer(connect => {
connections.push(connect)
connect.on("text", data => {
console.log("received: "+data);
connect.sendText(data);
broadcast(connections,data)
});
connect.on("close", (code, reason) => {
console.log("connection closed!");
});
connect.on('error', ()=>{
console.log("connection error!");
});
});
server.listen(POST, ()=>{
console.log("websocket server start success!");
});
The service address is: ws://127.0.0.1:8080
The port number is occupied and can be changed at will
Non-native, use sockjs, http service
The establishment steps are the same as those of the native ones, which need to be relied on, and are added directly on the basis of the previously established files.
client
<!doctype html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script src="http://cdn.jsdelivr.net/sockjs/1.0.1/sockjs.min.js"></script>
<style>
.box {
width: 300px;
float: left;
margin: 0 20px 0 20px;
}
.box div, .box input {
border: 1px solid;
-moz-border-radius: 4px;
border-radius: 4px;
width: 100%;
padding: 0px;
margin: 5px;
}
.box div {
border-color: grey;
height: 300px;
overflow: auto;
}
.box input {
height: 30px;
}
h1 {
margin-left: 30px;
}
body {
background-color: #F0F0F0;
font-family: "Arial";
}
</style>
</head>
<body lang="en">
<h1>Index</h1>
<div id="first" class="box">
<div></div>
<form><input autocomplete="off" value="Type here..."></input></form>
</div>
<script>
var sockjs_url = 'http://localhost:8080/echo';
var sockjs = new SockJS(sockjs_url);
$('#first input').focus();
var div = $('#first div');
var inp = $('#first input');
var form = $('#first form');
var print = function(m, p) {
p = (p === undefined) ? '' : JSON.stringify(p);
div.append($("<code>").text(m + ' ' + p));
div.append($("<br>"));
div.scrollTop(div.scrollTop()+10000);
};
sockjs.onopen = function() {
print('[*] open', sockjs.protocol);};
sockjs.onmessage = function(e) {
print('[.] message', e.data);};
sockjs.onclose = function() {
print('[*] close');};
form.submit(function() {
print('[ ] sending', inp.val());
sockjs.send(inp.val());
inp.val('');
return false;
});
</script>
</body>
</html>
Server
var http = require('http');
var sockjs = require('sockjs');
var current = [];
var echo = sockjs.createServer();
echo.on('connection', function(conn) {
current.push(conn)
conn.on('data', function(message) {
current.forEach((qq)=> {
// qq.write(JSON.stringify(message).replace(/\//g,''));
qq.write(message);
console.log(qq + conn + 'message')
})
});
conn.on('close', function() {
});
});
var server = http.createServer();
echo.installHandlers(server, {
prefix:'/echo'});
server.listen(8080);
Complete folder directory:
where server.js is the native server, and the node running
service address is: ws://127.0.0.1:8080
Among them, sockjs.js is http service, and the address of using node to run
the service is: http://localhost:8080/echo
After the two servers establish a connection, they will broadcast and send
Attach a test socket service address: http://wstool.js.org/