Skip to content

Instantly share code, notes, and snippets.

@whitecoop
Created September 5, 2017 00:20
Show Gist options
  • Save whitecoop/157702ab76fb8243720fb318abd85341 to your computer and use it in GitHub Desktop.
Save whitecoop/157702ab76fb8243720fb318abd85341 to your computer and use it in GitHub Desktop.
Web Socket Minimal Example
<html>
<head>
<title>Web Socket Testing</title>
<script>
// Create WebSocket connection.
const socket = new WebSocket('ws://localhost:8080');
// Connection opened
socket.addEventListener('open', function (event) {
socket.send('Hello Server!');
});
// Listen for messages
socket.addEventListener('message', function (event) {
console.log('Message from server: ', event.data);
});
</script>
</head>
<body></body>
</html>
// after installing: `npm install --save ws`
const WebSocket = require('ws');
const wss = new WebSocket.Server({ port: 8080 });
wss.on('connection', function connection(ws) {
ws.on('message', function incoming(message) {
console.log('received: %s', message);
ws.send("thanks for: " + message);
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment