前端 WebSocket,客户端主动连接,主动关闭

<!DOCTYPE html>
<html lang="en">
	<head>
		<meta charset="UTF-8">
		<title>webSocket小Demo</title>
	</head>
	<body>
		<div class="container">
			<div>
				<input type="text" id="msg">
				<button onclick="onOpen()">点击打开连接</button>
				<button onclick="sendMsg()">发送报文</button>
				<button onclick="onClose()">点击打开连接</button>
			</div>
		</div>
		<script>
			var ws;
			onOpen()
			
			function sendMsg() {
				let msg = document.getElementById('msg').value;
				ws.send(msg);
			}

			function onOpen() {
				ws = new WebSocket('ws://localhost:4399');
				ws.onopen = () => {
					console.log('状态打开...');
				}
				ws.onmessage = (res) => {
					console.log("数据:", res);
				};
				ws.onclose = () => {
					console.log('状态关闭...');
				}
			}

			function onClose() {
				ws.close()
			}
		</script>
	</body>

const WebSocketServer = require('ws').Server;
const wss = new WebSocketServer({ port: 4399 });
wss.on('connection', function (ws) {
    console.log('状态已经链接');
    ws.on('message', function (message) {
        ws.send('收到数据并返回:' + message);
    });
});
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值