switch socket with click on button

main
alex 2022-12-12 22:43:27 +01:00
parent 2127ad36a9
commit 64ec827369
2 changed files with 24 additions and 3 deletions

View File

@ -8,6 +8,7 @@
<script src="script.js"></script> <script src="script.js"></script>
</head> </head>
<body> <body>
<p>WS: <span id="ws"></span> <button id="change-ws">Change WS</button></p>
<p>UserID: <span id="userid"></span> <button id="copy-userid">Copy</button></p> <p>UserID: <span id="userid"></span> <button id="copy-userid">Copy</button></p>
<br> <br>

View File

@ -1,3 +1,8 @@
let ws = null
let wsAddress = "ws://localhost:"
let wsPort = 3000
window.onload = () => { window.onload = () => {
const msg = document.getElementById("msg") const msg = document.getElementById("msg")
const receiver = document.getElementById("receiver") const receiver = document.getElementById("receiver")
@ -23,16 +28,29 @@ window.onload = () => {
document.getElementById("receiver").value = "" document.getElementById("receiver").value = ""
} }
document.getElementById("change-ws").onclick = () => {
if (wsPort === 3000) {
wsPort = 3001
} else {
wsPort = 3000
}
if (ws.readyState == 1) {
ws.close()
}
}
connectWS() connectWS()
} }
let ws = null
function connectWS() { function connectWS() {
ws = new WebSocket("ws://localhost:3000/") ws = new WebSocket(wsAddress + wsPort)
ws.onopen = () => { ws.onopen = () => {
console.info("ws open", document.getElementById("userid")) console.info("ws open", document.getElementById("userid"))
document.getElementById("ws").innerHTML = ws.url
} }
ws.onmessage = (msg) => { ws.onmessage = (msg) => {
@ -46,7 +64,9 @@ function connectWS() {
} }
ws.onclose = (e) => { ws.onclose = (e) => {
console.log("ws closed", e.reason) if (e.reason.code === 1005) return
console.log("ws closed", e)
document.getElementById("userid").innerHTML = "" document.getElementById("userid").innerHTML = ""
setTimeout(() => connectWS(), 1000) setTimeout(() => connectWS(), 1000)
} }