Skip to content

Commit

Permalink
release: Version Packages
Browse files Browse the repository at this point in the history
  • Loading branch information
Marinerer committed Dec 3, 2024
1 parent 371c218 commit 15ddda0
Show file tree
Hide file tree
Showing 4 changed files with 123 additions and 323 deletions.
285 changes: 0 additions & 285 deletions libs/websocket/README.zh_CN.md

This file was deleted.

53 changes: 53 additions & 0 deletions libs/websocket/example/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>websocket</title>
</head>
<body>
<dl>
<dt>发送</dt>
<dd><input id="message" type="text" /></dd>
<dt>接收</dt>
<dd><textarea id="receive" readonly="readonly" rows="10" cols="50"></textarea></dd>
<dt>断开</dt>
<dd><input id="disconnect" type="button" value="断开" /></dd>
</dl>

<script type="module">
import WebSocketConnect from '../dist/index.js'
const $result = document.querySelector('#receive')

const ws = new WebSocketConnect('ws://localhost:30001')
ws.addEventListener('message', (e) => {
$result.value += e.data + '\n'
})
ws.onclose = () => {
$result.value += '连接已断开\n'
}
ws.onerror = (e) => {
$result.value += '连接发生错误\n'
}
ws.onopen = () => {
$result.value += '连接已建立\n'
}
ws.onreconnect = (e) => {
$result.value += `正在重连 (${e.detail.attempt})\n`
}
ws.onreconnecterror = (e) => {
$result.value += `重连结束 (${e.detail.attempt})\n`
}

document.querySelector('#disconnect').onclick = () => {
ws.close()
}
document.querySelector('#message').onkeydown = (e) => {
if (e.keyCode === 13) {
ws.send(e.target.value)
e.target.value = ''
}
}
</script>
</body>
</html>
32 changes: 32 additions & 0 deletions libs/websocket/example/server.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
const WebSocket = require('ws')

const port = 30001
const server = new WebSocket.Server({ port })

server.on('listening', () => {
console.log(`WebSocket server is listening on port ${port}`)
})

server.on('connection', (socket, req) => {
// const cli = req
console.log('WebSocket client connected')

socket.on('error', console.error)

socket.on('message', (message) => {
console.log('received: %s', message)

// Echo the message back to the client
if (message == 'error') {
throw new Error('happen unexpectedly')
} else if (message == 'ping') {
socket.send('pong')
} else {
socket.send(`Echo: ${message}`)
}
})

socket.on('close', () => {
console.log('WebSocket client disconnected')
})
})
Loading

0 comments on commit 15ddda0

Please sign in to comment.