<!DOCTYPE html>
<html>
<head>
<title>WebSocket Demo</title>
<style>
body {
margin: 0;
padding: 0;
height: 100vh;
display: flex;
flex-direction: row;
justify-content: space-between;
align-items: flex-start;
}
</style>
<script type="text/javascript">
var socket;
function init() {
var url = "ws://00.0.0.0:8005"; // WebSocket 服务器的 URL
socket = new WebSocket(url);
// 监听 WebSocket 连接建立事件
socket.onopen = function () {
console.log("WebSocket 连接已建立");
};
// 监听 WebSocket 接收到消息事件
socket.onmessage = function (event) {
displayMessage('接收消息: ' + JSON.parse(event.data).msgContent);
};
// 监听 WebSocket 连接关闭事件
socket.onclose = function () {
console.log("WebSocket 连接已关闭");
};
}
function sendMessage() {
var inputElement = document.getElementById("messageInput");
var message = inputElement.value;
displayMessage('发送消息: ' + message);
if (socket && socket.readyState === WebSocket.OPEN) {
socket.send(message);
}
inputElement.value = "";
}
function displayMessage(message) {
var displayArea = document.getElementById("displayArea");
displayArea.innerHTML += message + "<br>";
}
function handleKeyDown(event) {
if (event.key === "Enter" && !event.shiftKey) {
if (event.ctrlKey) {
var textarea = document.getElementById("messageInput");
textarea.value += "\n";
} else {
event.preventDefault();
sendMessage()
}
}
}
</script>
</head>
<body onl oad="init()">
<div style=" width: 30%; height: 40%;">
<textarea type="text" style="width:100%;margin:20px;height: 90%;" id="messageInput"
onkeydown="handleKeyDown(event)"></textarea><br/>
<button style="width:30%;margin-left:20px;" onclick="sendMessage()">发送</button>
</div>
<div id="displayArea" style="margin-top:20px;
width: 60%;
height: 100%;
word-wrap: break-word; /* 在单词内换行 */
white-space: pre-wrap; /* 保留空格和换行符,并在必要时换行 */"></div>
<br/><br/>
</body>
</html>
标签:function,WebSocket,socket,textarea,快捷键,var,message,event,回车
From: https://blog.51cto.com/u_11288266/9145937