How to do it...

In server.js, let's begin by requiring our dependencies:

const http = require('http') 
const fs = require('fs')
const ws = require('ws')

Next we want to load public/index.html into memory (we'll write index.html shortly), create an HTTP server, and then enhance it with a WebSocket server:

const app = fs.readFileSync('public/index.html') 
const server = http.createServer((req, res) => {
res.setHeader('Content-Type', 'text/html')
res.end(app)
})
const wss = new ws.Server({server})

Now that we have our WebSocket server instance (wss), we can listen to its connection event:

wss.on('connection', (socket) => { 
socket.on('message', (msg) => {
console.log(`Received: ${msg}`)
console.log(`From IP:
${socket.upgradeReq.connection.remoteAddress}`)
if (msg === 'Hello') socket.send('Websockets!')
})
})

Finally, let's tell our HTTP server to listen on port 8080:

server.listen(8080) 

Now for our frontend code.

Let's place the following in public/index.html:

<input id="msg"><button id="send">Send</button> 
<div id="output"></div>

Now in the same public/index.html, we'll place our client-side JavaScript.

At the bottom of public/index.html, let's add the following:

<script> 
(function () {
var ws = new WebSocket('ws://localhost:8080')
var output = document.getElementById('output')
var send = document.getElementById('send')

function log (event, msg) {
return '<div>' + event + ': ' + msg + '</div>';
}

send.addEventListener('click', function () {
var msg = document.getElementById('msg').value
ws.send(msg)
output.innerHTML += log('Sent', msg)
})

ws.onmessage = function (e) {
output.innerHTML += log('Received', e.data)
}

ws.onclose = function (e) {
output.innerHTML += log('Disconnected', e.code + '-' + e.type)
}

ws.onerror = function (e) {
output.innerHTML += log('Error', e.data);
}
}())
</script>

Let's try it out by starting our server:

$ node server.js

Then going to http://localhost:8080 in our browser, typing Hello in the textbox, and clicking on the Send button.

The terminal should then output something like this:

Received: Hello 
From IP: ::1

On other systems (where IPv4 is the default), the IP might be 127.0.0.1 instead.

Our browser should display something like the following:

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset