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.com); so the websocket call coming 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.
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 incoming 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}`);
});
Related
this code is in my nodejs backend (https://backend.example.com) server.js file:
const WebSocket = require('ws');
const server = new WebSocket.Server({
port: 7500
},
() => {
console.log('Server started on port 7500');
}
);
This code is in my nextjs frontend chat (http://frontend.example.com/chat) page file:
React.useEffect(() => {
ws.current = new WebSocket("ws://localhost:7500");
ws.current.onopen = () => {
console.log("Connection opened");
setConnectionOpen(true);
};
ws.current.onmessage = (event) => {
const data = JSON.parse(event.data);
setMessages((_messages) => [..._messages, data]);
};
return () => {
console.log("Cleaning up...");
ws.current.close();
};
}, []);
it works fine in localhost but on deployed live server, the websocket is not communicating, what is wrong with my code?
EDIT: Have updated the useEffect() to:
React.useEffect(() => {
ws.current = new WebSocket("wss://backend.example.com:7500");
ws.current.onopen = () => {
console.log("Connection opened");
setConnectionOpen(true);
};
ws.current.onmessage = (event) => {
const data = JSON.parse(event.data);
setMessages((_messages) => [..._messages, data]);
};
return () => {
console.log("Cleaning up...");
ws.current.close();
};
}, []);
but still it does not work, If I visit the https://backend.example.com I get Upgrade Required
If this is the code you deploy on live server, then I think the following points have to be addressed.
On the client you point to localhost, you should have the server name, instead.
And more important, in local you're publishing the app in http, while in live server it is in https?
In this case the WebSocket url should change the protocol from ws to wss.
UPDATE
Another point of attention is your server.
I don't see code that is handling the connection, according to the documentation example.
import WebSocket from 'ws';
const ws = new WebSocket('ws://www.host.com/path');
// This handle the co
ws.on('open', function open() {
ws.send('something');
});
ws.on('message', function message(data) {
console.log('received: %s', data);
});
If this is not the library you're using, please update your question whit all the references to the library you're using or the documentation you're referring to to write your code.
About the port, there is nothing specific about the port, the only issue is that you can have the port blocked, on the firewall of your client or on the network gateway of your server.
But that depends on your environment, you should check if the port is usable.
A simple test is to try a small server with an html page published on the 7500 port on your server. If you can see the page the port is ok.
And more you should not use the same port of your server, pick another one, because the http server is reserving that port, and your WebSocket will fail attempting to bind.
But you should see an error on the server if that happened.
If you want to use your application server port, instead of starting a different server then follow this example.
I want to use socket.io in localhost which is my development environment:
client code:
const socket = io.connect('https://localhost:4000/');
socket.emit('trim-movie/go', data);
socket.on('trim-movie-response', trimResponse);
server :
const server = app.listen(port, () => console.log('server is online...'));
const io = socket(server);
io.on("connection", (socket) => {
socket.on('trim-movie/go', (data) => trimMovie(data, socket));
});
But I get this error:
socket.io.js?v=1:1415 GET
https://localhost:4000/socket.io/?EIO=4&transport=polling&t=OI2OmiX
404 (Not Found)
How to fix this?
Your client shows an https URL. Your server is starting an http server, NOT an https server because app.listen() only starts an http server. There's no way and https url will connect to an http server so these will ever match up.
Change the client to:
const socket = io.connect('http://localhost:4000/');
Or, if your page is already loaded from that same server, you can just use:
const socket = io();
and the client will get the domain and port from the URL of the containing web page.
Also make sure that the server-side port variable is set to 4000.
I have a simple snippet on the front end as follows which I can verify is working. I can do this by changing the port to something other than 3000 and it will error.
It is definitely finding the server at that port:
// Create WebSocket connection .. will error if I change the port
const socket = new WebSocket('ws://localhost:3000');
console.log('DEBUG: Web socket is up: ');
// Connection opened
socket.addEventListener('open', function (event) {
socket.send('Hello Server!');
});
I am using ws-express on the server side as follows. This was the minimal example given in the NPM docs:
const expressWs = require('express-ws')(app);
app.ws('/echo', (ws, req) => {
ws.on('message', (msg) => {
ws.send(msg);
});
});
However, the open event on the client never fires. I would like to send messages from the client to the server, but I assume, that I need an open event to fire first.
I'm using ws library to handle Websocket connections client-side.
Here's example from ws docs (https://github.com/websockets/ws#usage-examples):
const WebSocket = require('ws');
const ws = new WebSocket('ws://www.host.com/path');
ws.on('open', function open() {
ws.send('something');
});
ws.on('message', function incoming(data) {
console.log(data);
});
The problem is that this program exits after receiving just the first message from server.
How do I make it run and listen for messages indefinitely?
I'm looking for a way to send data from my socket, e.g.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.