Last active
November 16, 2019 03:54
-
-
Save syuji-higa/2a91df1aed2dedf4f89f18935fc46b79 to your computer and use it in GitHub Desktop.
Node.js - WebSocket demo
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!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> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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