Server-side Web Sockets Application
You can use any programming languages to write a Web Sockets server. In our course, we will use JavaScript for sure. Specifically, we will use a NPM package: ws.
npm install ws
Let us look at a simple example. Here is the code at the server side.
WebSocket=require('ws');
const wss = new WebSocket.WebSocketServer({ port: 8080 });
wss.on('connection', function connection(ws) {
ws.on('message', function message(data) {
console.log('received: %s', data);
});
ws.send('something');
});
Then, we can run the following code at the client-side browser (e.g., in the console).
ws = new WebSocket("ws://localhost:8080");
ws.onopen = function (event) {
ws.send("Hello from the client!");
};
ws.onmessage = function (event) {
console.log(event.data);
}
Remember to run ws.close()
to close the socket afterwards.
You can also use NPM ws
to create a client as well. See below:
WebSocket=require('ws');
const ws = new WebSocket('ws://localhost:8080');
ws.on('open', function open() {
ws.send('something');
});
ws.on('message', function message(data) {
console.log('received: %s', data);
});