gohttp/public/index.html

46 lines
1.4 KiB
HTML
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>WenSocket</title>
<style>
div{
width: 200px;
height: 200px;
border:1px solid;
margin-top: 5px;
}
</style>
</head>
<body>
<input type="text" placeholder="请输入内容">
<button>提交</button>
<div></div>
<script>
const input = document.querySelector('input')
const button = document.querySelector('button')
const div = document.querySelector('div')
//创建WebSocket实例
const socket = new WebSocket("ws://localhost:8080/ws")
//监听服务是否链接
socket.addEventListener('open',()=>{
div.innerHTML = "服务链接成功"
})
//button触发点击事件将input框中的内容发送至websocket
//查看websocket是否接收到数据chrome F12打开控制台》Network》WS》echo.websocket.org》messages
button.addEventListener('click',()=>{
const value = input.value
socket.send(value)
})
// 将接收到的数据插入到div中
socket.addEventListener('message',(e)=>{
console.log(e)
div.innerHTML = e.data
})
</script>
</body>
</html>