how to set specific ip in websocket server?(node.js) - javascript

I can set the port on the Web socket server as shown below.
const wss = new WebSocketServer({
port: rrPort,
});
(I tried set with 'host' and 'path' but it doesn't work.)
Now I have to set specific ip on the Web socket server.
I have two LAN so also IPs.
I wanna set with one of IPs but I can't.
I can get web socket server ip with connected PC as shown below.
const ip = ws._socket.remoteAddress.slice(7);

You need to set the ip when you create http server which you pass to WebSocketServer to use.
var WebSocketServer = require('websocket').server;
var http = require('http');
var server = http.createServer(...);
// this is where you set the ip to listen to
server.listen(8080, '192.168.0.1', function() {
});
wsServer = new WebSocketServer({
httpServer: server,
port: 1234
});

Related

How to get the link of the created server in the http.createServer() function?

How to get the link of the created server in the http.createServer() function?
I am trying to use the http package from node.js and use the createServer() function, then I want to print the server's link with the port, like this:
const createServer = http.createServer();
const server = createServer.listen(port);
And then get the link from the createServer variable like http://localhost or from a repl.it/replit.com link
.
this is my code in JS:
const port = 1234;
const createServer = http.createServer();
const server = createServer.listen(port);
const websocket = new web({ httpServer: server });
console.log(createServer); // This doesnt print the server link
You can get the information about the server by calling server.address():
console.dir(server.address());
//{ address: '::', family: 'IPv6', port: 1234 }
Since you didn't specify a host when creating the server, the default one will be used which according to the documentation:
If host is omitted, the server will accept connections on the unspecified IPv6 address (::) when IPv6 is available, or the unspecified IPv4 address (0.0.0.0) otherwise.

Javascript: Can I open websocket server connection at random port

I want to create webserver socket connection at random port. And I want to return server port to calling application or just print it in terminal.
The typical code to create a server connection is as below.
const WebSocket = require('ws');
const wss = new WebSocket.Server({ port: 0 });
wss.on('connection', function connection(ws) {
ws.on('message', function incoming(message) {
console.log('received: %s', message);
});
ws.send('something');
});
So I am trying to create server at port 0. I assume it will create server at random port. How do I get that random port?
I want to know the port number, as soon as server socket is created.
Now I am able to create the websocket server at random port and able to get the port number as well. Not sure if it is the right way, but it works.
const http = require('http');
const WebSocket = require('ws');
const url = require('url');
const server = http.createServer();
const wss = new WebSocket.Server({ noServer: true });
wss.on('connection', function connection(ws) {
console.log(wss);
});
server.on('upgrade', function upgrade(request, socket, head) {
const pathname = url.parse(request.url).pathname;
wss.handleUpgrade(request, socket, head, function done(ws) {
wss.emit('connection', ws, request);
});
});
server.listen(0, '127.0.0.1', function incoming() {console.log (server.address().port);});
Websocket works with http/s on port 80 or 443. The server may listen on any port it chooses, but if it chooses any port other than 80 or 443, it may have problems with firewalls and/or proxies. Browsers generally require a secure connection for WebSockets, although they may offer an exception for local devices.

Client unable to connect to server with socket.io

I'm having trouble with being able to connect to my node.js server from an external domain. It works fine when running it locally using the http web server through node however when connecting externally, it loads the socket.io.js file just fine but when trying to use the socket it removes the port from the URL and cannot connect.
Instead of doing this in the network requests:
http://external-domain.com:3000/socket.io/?EIO=3&transport=polling&t=M06GOUU
it does this:
http://external-domain.com/socket.io/?EIO=3&transport=polling&t=M06GOUU
I'm not sure how to make it not remove the port from the connection. How do I go about fixing this?
SERVER
const path = require('path');
const http = require('http');
const express = require('express');
const socketIO = require('socket.io');
const publicPath = path.join(__dirname, '../public');
var app = express();
var server = http.createServer(app);
var io = socketIO(server);
app.use(express.static(publicPath));
server.listen(3000, () => {
console.log(`Server is up on port 3000`);
});
CLIENT SCRIPT TAG
<script src="http://external-domain.com:3000/socket.io/socket.io.js"></script>
CLIENT JS ON A DIFFERENT DOMAIN
var socket = io();
socket.connect('http://external-domain.com:3000');
socket.on('connect', function () {
console.log('Connected to server.');
});
Change from this:
var socket = io();
socket.connect('http://external-domain.com:3000');
to just this:
var socket = io("http://external-domain.com:3000");
And, you don't use the socket.connect() as you will already have requested the connection with the io("http://external-domain.com:3000"); call.
Explanation
The code:
var socket = io();
uses the page URL to connect to a socket.io server at that origin. That is not what you want (apparently).
If you wanted to use the .connect() method, it would be like this:
var socket = io.connect("http://external-domain.com:3000");
Note: var socket = io(url) is simply a shortcut for var socket = io.connect(url).
socket.connect() does not accept a URL as a parameter so you simply weren't using that correctly. It's just a synonym for socket.open().
Use io.connect("url")
var socket = io.connect("http://external-domain.com:3000", { rejectUnauthorized: false });
// { rejectUnauthorized: false } is an optional parameter.
Hope this works for you.

node.js Cannot GET /socket.io

I have the following app with express/socket.io (the app is listening and live without any errors).
When I http-request it I get the following error:
GET http://xxxxxxx.com:3035/socket.io/1/?t=1449090610579 400 (Bad Request)
And on the socket.io reponse at http://xxxxxxx.com:3035/socket.io I get:
Cannot GET /socket.io
app.js:
var express = require('express'),
http = require('http'),
sio= require('socket.io'),
fs=require('fs'),
app = express();
var mysql = require('mysql');
var connection = mysql.createConnection({
host: 'localhost',
user: 'xxxxxxx',
password: 'xxxxxxx',
database: 'xxxxxxxxx'
}
);
connection.connect();
// Start the server
var server=app.listen(3035, function () {
console.log("Express server listening on port %d",3035);
});
app.io=io=sio.listen(server);
.
.
.
on the client side:
var socket = io.connect('http://xxxxxx.com:3035');
Your sio is a function. You need to call it with your server as an argument.
Add
server=require('http').Server(app)
sio=require('socket.io')(server)
io.connect() takes a URL such as http://example.com:3035.
You are passing xxxxxx.com:3035 which is not a proper URL form.
Also, note that if you're just trying to connect to the same server and port as the web page came from, you can just use:
io()
or
io.connect()
And the socket.io library will connect back to the same host and port as the web page.
You should initialize default connection on client side by
io.connect( "/" );
According to documentation by default socket.io will connect to the same host and port where rendered webpage is. The / in the path states to connect to default namespace.

Websocket server on subdomain only

I'm trying to have a websocket server on a subdomain so the client would point to something like 'ws://ws.mydomain.com'.
I'm using the subdomain module to handle normal get requests to subdomains but not sure how to consolidate the two. Any ideas on how I can approach this?
The WebSocketServer can take a server object, but can't figure it out.
var WebSocketServer = require('ws').Server
var express = require('express');
var subdomain = require('subdomain');
var app = express();
var wss = new WebSocketServer({port: 8081, server: http.Server});
app.use(subdomain({ base: 'mydomain.com', removeWWW: true}));
wss.on('connection', function(ws){
console.log('a connection!');
});
app.get('/subdomain/unrelatedsub', function(req, res){
res.send("hello unrelated subdomain page");
});
app.listen(80);
Link to WS documentation
From the web socket protocol:
The WebSocket Protocol attempts to address the goals of existing
bidirectional HTTP technologies in the context of the existing HTTP
infrastructure; as such, it is designed to work over HTTP ports 80
and 443 as well as to support HTTP proxies and intermediaries, even
if this implies some complexity specific to the current
environment.
Express 3 exposes the app as a request handler, you must instantiate a http.Server first which you can pass the express app into, and then you setup your sockets, as the ws:// protocal can share the HTTP port you listen on, just as wss:// would share the HTTPS port.
Try something closer to this, I will test when get a chance if you haven't responded:
var WebSocketServer = require('ws').Server
var express = require('express');
var http = require('http')
var app = express();
app.use(subdomain({ base: 'mydomain.com', removeWWW: true}));
var server = http.createServer(app);
server.listen(8080);
var wss = new WebSocketServer({server: server});
wss.on('connection', function(ws){
console.log('a connection!');
});
app.get('/subdomain/unrelatedsub', function(req, res){
res.send("hello unrelated subdomain page");
});

Categories

Resources