最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - creating websocket server in electron node for external client request - Stack Overflow

programmeradmin7浏览0评论

I am trying to create a websocket server that listen to an external websocket clinet. the point is I am laoding a web base application inside my browser window in electron. for example : win.loadURL(www.something); so the websocket call ing from this url meaning if I getinto this url in browser in my network tab I see websocket call is keep calling but there is no server. so I want to implement the server inside my electron app main.js. and here is my code:

const WebSocket = require("ws");
const wss = new WebSocket.Server({port: 8102});

wss.on("connection", ws => {
    ws.on("message", message => {
        console.log("received: %s", message);
    });
    ws.send("something");
});

so far I did not get any success. any help would appriciate.

I am trying to create a websocket server that listen to an external websocket clinet. the point is I am laoding a web base application inside my browser window in electron. for example : win.loadURL(www.something.); so the websocket call ing from this url meaning if I getinto this url in browser in my network tab I see websocket call is keep calling but there is no server. so I want to implement the server inside my electron app main.js. and here is my code:

const WebSocket = require("ws");
const wss = new WebSocket.Server({port: 8102});

wss.on("connection", ws => {
    ws.on("message", message => {
        console.log("received: %s", message);
    });
    ws.send("something");
});

so far I did not get any success. any help would appriciate.

Share Improve this question asked Nov 13, 2019 at 18:13 Samira ArabgolSamira Arabgol 3892 gold badges9 silver badges31 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 5

you need to start your http server mine looks like this:

import http from "http";
import * as WebSocket from "ws";

const port = 4444;
const server = http.createServer();
const wss = new WebSocket.Server({ server });

wss.on("connection", (ws: WebSocket) => {
  //connection is up, let's add a simple simple event
  ws.on("message", (message: string) => {
    //log the received message and send it back to the client
    console.log("received: %s", message);
    ws.send(`Hello, you sent -> ${message}`);
  });

  //send immediatly a feedback to the ining connection
  ws.send("Hi there, I am a WebSocket server");
});

//start our server
server.listen(port, () => {
  console.log(`Data stream server started on port ${port}`);
});
发布评论

评论列表(0)

  1. 暂无评论