原生socket服务
步骤
- 新建一个文件夹
- 建立三个文件(依赖)
expressSocketSever.js
package-lock.json
package.json
3.打开编辑器终端 ,执行 npm i (或者yarn i ),前提是有包管理器npm或者yarn
客户端
<!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>
服务端
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!");
});
服务地址为: ws://127.0.0.1:8080
端口号占用可以随意换
非原生,使用sockjs, http服务
建立步骤与原生相同,需要依赖,直接在前面建立的文件基础上新加
客户端
<!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>
服务端
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);
完整文件夹目录:
其中server.js为原生服务端,使用node运行
服务地址为: ws://127.0.0.1:8080
其中sockjs.js为http服务,使用node运行
服务地址为: http://localhost:8080/echo
两个服务端建立连接之后,都会进行广播发送文章来源:https://www.toymoban.com/news/detail-589873.html
附一个测试socket服务的地址:http://wstool.js.org/文章来源地址https://www.toymoban.com/news/detail-589873.html
到了这里,关于nodej.s 搭建一个socket服务(原生和sockjs)的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!