Javascript  

 

 

 

 

 

Simple WebSocket

 

this code is created first by chatGPT on Jan 10 2023 (meaning using chatGPT 3.5) and then modified a little bit my me. The initial request that I put into chatGPT is as follows :

 

create a simple java script for websocket. create a server and client as separate files. Client and Server exchange the messages in JSON format.

NOTE : It is not guaranteed that you would have the same code as I got since chatGPT produce the answers differently depending on the context. And it may produce the different answers everytime you ask even with the exact the same question.

NOTE : If you don't have any of your own idea for the request, copy my request and paste it into the chatGPT and put additional requests based on the output for the previous request. I would suggest to create a new thread in the chatGPT and put my request and then continue to add your own request.

 

 

ws_simpleserver.js

const WebSocket = require('ws');

 

const wss = new WebSocket.Server({ port: 8080 });

 

wss.on('connection', (ws) => {

    console.log('Client connected');

    ws.on('message', (message) => {

        let data = JSON.parse(message);

        console.log(`Received message: ${data.text}`);

        data.text = `Echo: ${data.text}`

        ws.send(JSON.stringify(data));

    });

    ws.on('close', () => {

        console.log('Client disconnected');

    });

});

 

 

ws_simpleclient.js

const WebSocket = require('ws');

 

const ws = new WebSocket('ws://localhost:8080');

 

ws.on('open', () => {

    console.log('Connected to server');

    let data = {

        text: 'Hello, server!'

    }

    ws.send(JSON.stringify(data));

});

 

ws.on('message', (message) => {

    let data = JSON.parse(message);

    console.log(`Received message: ${data.text}`);

});

 

ws.on('close', () => {

    console.log('Disconnected from server');

});

 

 

I tested this script with nodejs on Windows 11 as shown below. I am assuming that you have nodejs and required package (ws in this case) properly installed in your computer.