- Server: https://github.com/websockets/ws#server-example
- Client: https://developer.mozilla.org/en-US/docs/Web/API/WebSocket
In the client JS console: socket.send("hi");
It'll log in the server and come back to the client with thanks.
In the client JS console: socket.send("hi");
It'll log in the server and come back to the client with thanks.
<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); | |
}); | |
}); |