Skip to content

Instantly share code, notes, and snippets.

@syuji-higa
Last active November 16, 2019 03:54
Show Gist options
  • Save syuji-higa/2a91df1aed2dedf4f89f18935fc46b79 to your computer and use it in GitHub Desktop.
Save syuji-higa/2a91df1aed2dedf4f89f18935fc46b79 to your computer and use it in GitHub Desktop.
Node.js - WebSocket demo
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>title</title>
</head>
<body>
<button type="button" id="btn">Send</button>
<script>
const socket = new WebSocket('ws://localhost:9999')
socket.addEventListener('error', () => {
console.log('error')
})
socket.addEventListener('open', () => {
console.log('connect')
})
socket.addEventListener('message', (e) => {
console.log(`message: ${e.data}`)
})
document.getElementById('btn').addEventListener('click', () => {
socket.send('Hellow World!')
})
</script>
</body>
</html>
const WebSocket = require('ws')
const wss = new WebSocket.Server({ port: 9999 })
wss.on('connection', (ws) => {
console.log('connect')
ws.on('message', (message) => {
console.log(`message: ${message}`)
})
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment