node搭建简易的websocket服务
Posted ymwu
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了node搭建简易的websocket服务相关的知识,希望对你有一定的参考价值。
http协议单向请求,只能客户端向服务器发送消息,然而websocket一旦双方建立连接就可以双方通信,更加深层次的用法是websocket可以做基础,然后不同的客户端可以通过websocket连接可以实现实时通信,同时结合webrtc相关技术可以实现音视频的双向连接。
在此只做简单的websocket连接。
需要安装ws: npm install ws
客户端代码:
index.html:
<html lang="en">
<head>
<meta charset="utf-8">
<meta id="theme-color" name="theme-color" content="#fff">
<base target="_blank">
<title>WebSocket</title>
<link rel="stylesheet" href="main.css">
</head>
<body>
<div id="container">
<button id="connectButton">Connect</button>
<button id="disconnectButton" disabled>Disconnect</button>
<div id="sendText">
<label for="textInput">Send text:</label>
<input id="textInput" type="text" />
</div>
<button id="sendButton" disabled>Send</button>
<div id="output">
<label for="log">Response:</label>
<div id="log" class="log"></div>
</div>
<script src="main.js"></script>
</div>
</body>
</html>
main.js:
‘use strict‘;
var ws, serverInput, textInput, log,
connectButton, disconnectButton, sendButton;
serverInput = document.getElementById(‘serverInput‘);
textInput = document.getElementById(‘textInput‘);
log = document.getElementById(‘log‘);
connectButton = document.getElementById(‘connectButton‘);
disconnectButton = document.getElementById(‘disconnectButton‘);
sendButton = document.getElementById(‘sendButton‘);
connectButton.addEventListener(‘click‘, clickConnect, false);
disconnectButton.addEventListener(‘click‘, clickDisconnect, false);
sendButton.addEventListener(‘click‘, clickSend, false);
function clickConnect() {
ws = new WebSocket("ws://127.0.0.1:8888");
ws.onopen = function(evt) {
logMessage(‘‘, ‘Connected‘);
connectButton.disabled = true;
disconnectButton.disabled = false;
sendButton.disabled = false;
};
ws.onclose = function(evt) {
logMessage(‘err‘, ‘Disconnected‘);
connectButton.disabled = false;
disconnectButton.disabled = true;
sendButton.disabled = true;
};
//客户端接收到服务端返回的信息 ws.onmessage = function(evt) {
logMessage(‘msg‘, ‘Received: ‘ + evt.data);
};
ws.onerror = function(evt) {
logMessage(‘err‘, ‘Error: ‘ + evt.data);
};
}
function clickDisconnect() {
ws.close();
}
function clickSend() {
logMessage(‘send‘, ‘Sent: ‘ + textInput.value);
ws.send(textInput.value);
}
function logMessage(type, msg) {
log.innerHTML += ‘<p class="‘ + type + ‘">‘ + msg + ‘</p>‘;
}
服务端代码
index.js:
const WebSocketServer = require(‘ws‘).Server;
const wss = new WebSocketServer({ port: 8888 });
// 一旦与之连接就出发connection事件
wss.on(‘connection‘, function (ws) {
console.log("connected");
// 客户端反馈给服务端的信息
ws.on(‘message‘, function (message) {
// 服务器给用户反馈会信息
ws.send(message);
console.log(message);
});
})
console.log("websocket server running at ")
以上是关于node搭建简易的websocket服务的主要内容,如果未能解决你的问题,请参考以下文章