<!DOCTYPE html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>websocket demo</title> <meta name="viewport" content="width=device-width, initial-scale=1" /> <style> .row { margin: 1rem } </style> </head> <body> <a class="btn btn-info" href="\fun"><span class="glyphicon glyphicon-home"></span> 返回</a> <div class='row'>发送方: <select id='sender'> <option value="Bob" selected>Bob</option> <option value="Alice">Alice</option> <option value="Jack">Jack</option> </select> </div> <div class='row'>接收方: <select id='receiver'> <option value="Bob">Bob</option> <option value="Alice" selected>Alice</option> <option value="Jack">Jack</option> </select> </div> <textarea id='msg' class='row' rows="10" cols="30"></textarea> <div class='row'> <button id='sendBtn'>发送</button> </div> <h3 class='row'>收到的消息:</h3> <div id='conversation' class='row'></div> <script> var sender = document.getElementById('sender'); var receiver = document.getElementById('receiver'); var conversation = document.getElementById('conversation'); var sendBtn = document.getElementById('sendBtn'); var socket = null; var createSocket = function () { if (socket) { socket.close(); } var url = 'ws://' + window.location.host + '/ws/' + sender.options[sender.selectedIndex].value; socket = new WebSocket(url); socket.onopen = function () { console.log('connected to ' + url); } socket.onmessage = function (event) { var data = JSON.parse(event.data); conversation.innerHTML = conversation.innerHTML + data.from + ':' + data.content + '<br/>'; } socket.onclose = function () { console.log('close connect to' + url); } }; var sendMessage = function () { var msg = document.getElementById('msg').value; var bd = JSON.stringify({ from: sender.options[sender.selectedIndex].value, content: msg, to: receiver.options[receiver.selectedIndex].value }) console.log(bd) fetch('/rest/message', { method: 'POST', headers: { 'Content-type': 'application/json', }, body: bd }).then(res => res.json()).then(data => { if (!data.succeed) { alert(data.msg); } }) }; sender.onchange = function () { createSocket(); } sendBtn.onclick = function () { sendMessage(); } createSocket(); </script> </body>