简体   繁体   中英

NodeJS as Websocket client using ws

I need to send a message to a websocket server through request POST. The client is not a browser but a Node server.

I'm new to websocket.

When I run the code below.

var WebSocket = require("ws");
const express = require("express");
var app = express();

const client = new WebSocket(process.env.URL);
client.on("error", handleError);

client.onopen = () => {
  client.send("Message From Client");
};

function handleError(error) {
  console.log(error);
}

app.get("/echo", async function (req, res) {
  client.once("connection", function connection(cli) {
    cli.send(msg);
    res.send("send");
  });
});

app.listen(3333, function () {
  console.log("Example app listening on port 3333!");
});

It shows the error

Error: write EPROTO 19524:error:1408F10B:SSL routines:ssl3_get_record:wrong version number:c:\ws\deps\openssl\openssl\ssl\record\ssl3_record.c:332:

    at WriteWrap.onWriteComplete [as oncomplete] (internal/stream_base_commons.js:92:16) {
  errno: 'EPROTO',
  code: 'EPROTO',
  syscall: 'write'
}

I'm not sure how to do it with express, but it should be similar to https. Here is how to do it with https.

Basically it has to be the https server that should listen on certain port and also have certs and keys as option passed to it. Then you would pass the https server to websocket server .

When client connects, it'll connect to https and then upgrade to WSS.

Which means your client application can connect to wss://test.mysite.com:1234 .

const https = require('https')   

const options = {
  cert: fs.readFileSync('/etc/ssl/test.mysite.com/cert.pem'),
  key: fs.readFileSync('/etc/ssl/test.mysite.com/privkey.pem'),
  ca: fs.readFileSync('/etc/ssl/test.mysite.com/chain.pem')
};

const httpsServer = https.createServer(options);

httpsServer.listen(1234, () => console.log('Https Server running on port 1234'));

var ws = new WebSocket.Server({
  server: httpsServer
});

ws.on('connection', socket => {
  console.log('Conencted')
});

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