简体   繁体   中英

Send data from Serverside Nodejs to Client Side (Not on socket)

I'm looking for a way to send data from my socket, eg example.com:8000 to my web server not on the socket example.com/index.php. I've been looking around at code, but I haven't found any answers. If you make sample code, could you display the var x which is = to 2 from Nodejs to the client?

Thanks in advance.

If you're using NodeJS as the server, then I recommend using this package: npm ws , it's a super light Web Socket for server side.

Now, to your example:

Server Side:

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('something');
});

Client side

const socket = new WebSocket('ws://127.0.0.1:8080/');
    socket.onopen = () => {
        console.log("I'm open!");
        socket.send('Sending from client');
    }
    socket.onmessage = (message) => {
        console.log('Received: ', message);
        console.log('Received Data: ', message.data);
    }
  • You'll see a console.log on the server that says "received: Sending from client"
  • You'll see two console.logs on the client saying:

    Received: MessageEvent {isTrusted: true, data: "something", origin: "ws://127.0.0.1:8080", lastEventId: "", source: null, …}

    AND

    Received Data: something

The data received "something" was emitted from the server on ws.send('something'); , you can change that to a JSON type string and then parsing the message.data on the client with JSON.parse(message.data)

NOTE: On client, WebSocket() is native API, so you don't have to import anything, unlike the NodeJS server, where the NPM package is desirable.

You can actually test the client side though your developer console.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM