Creating remote socket.io client in js format - node.js

I am using sockets.io with nodejs server to send/receive events between client and server.It works well on local pc but the issue comes when i have to connect a remote client to it and i dont need to use frontend template file or html. In that case, how can i define io() object i.e. a socket connection because without it i cannot access my nodeserver. Currently i have created a js file on remote client and it looks like this:
`var socket=io.connect('http://a.b.c.d:3000');
var name="alice";
socket.emit('ping',(name)=>{
socket.on('pong', reply);
console.log(reply);
});`

Web Sockets work over the HTTP protocol, so you need to run a server for it.

Related

socket.io client works in browser but not in node.js

The following code only works in the browser. It does not work in node.js
let socket1 = io('http://localhost:3031/nsp')
socket1.on("connect", (error) => {
console.log("socket1: connect")
});
I am connecting to a netty-socketio (v1.7.7) java server. I am able to connect to the root namespace on both browser and node.js clients and everything works as expected. However, if I try to connect to a namespace, only the browser client can connect as expected.
Furthermore, I can see on the server that the node.js client (v2.4.0) is connecting to the root namespace when it should be connecting to the named namespace "nsp". As such, the clients join the root namespace and seemingly never join the "nsp" namespace.
On further inspection, the only event I can get to fire on the node.js client, when specifying a namespace, after connecting is "ping" all other events (connect,connect_error,error,reconnect...) never trigger.
Update: the above code works when connecting to a node.js server, so the issue appears to be with the netty-socketio server.
Here is how the netty server is initialized:
Configuration config = new Configuration();
config.setHostname("localhost");
config.setPort(3031);
server = new SocketIOServer(config);
server.addNamespace('/nsp')
I finally figured it out. I had to revert the node.js client version to 1.7.4 (https://www.npmjs.com/package/socket.io-client/v/1.7.4) to get it to work. Not sure why I was forced to use such an old client to be able to use namespaces.

Websocket server running fine but cannot connect from client (what url should I use?)

OK this is very simple to anyone who's used websocket and nodejs.
I have created a websocket server named ws_server.js and put it in C:\Program Files (x86)\nodejs where I have installed the nodejs framework. I started the server and it is running and it says it's listening on port 8080. So far so good, I have the server running.
Now I simply want to connect to it from client code so that I can do all that lovely stuff about capturing events using event listeners etc. The problem is, embarassingly, I cannot figure out what URL to use to connect to my websocket server.
function init() {
testWebSocket();
}
function testWebSocket() {
websocket = new WebSocket("ws://localhost:8080/"); // WHAT URL SHOULD BE USED HERE?
websocket.onopen = function(evt) { alert("OPEN") };
websocket.onclose = function(evt) { alert("CLOSE") };
websocket.onmessage = function(evt) { alert("MESSAGE") };
websocket.onerror = function(evt) { alert("ERROR") };
}
function doSend(message) {
// this would be called by user pressing a button somewhere
websocket.send(message);
alert("SENT");
}
window.addEventListener("load", init, false);
When I use ws://localhost:8080 the only events that trigger are CLOSE and ERROR. I cannot get the client to connect. I must be missing something very simple. Do I need to set up my nodejs folder in IIS for example and then use that as the URL?
Just to reiterate, the websocket server is running fine, I just don't know what URL to use to connect to it from the client.
EDIT: The websocket server reports the following error.
Specified protocol was not requested by the client.
I think I have got it working by doing the following.
var websocket = new WebSocket("ws://localhost:8080/","echo-protocol");
The problem being that I needed to specify a protocol. At least now I get the onopen event. ...if nothing much else
I was seeing the same error, the entire web server goes down. Adding the protocol fixes it but leaves me wondering why it was implemented this way. I mean, one bad request should not bring down your server.
You definitely have to encase it a try/catch, but the example code provided here https://www.npmjs.com/package/websocket (2019-08-07) does not. This issue can be easily avoided.
I just wanted to share a crazy issue that I had. I was able to connect to a websocket of an old version of a 3rd party app in one computer, but not to a newer version of the app in another.
Moreever, even in new computer with the new version of the app, The app was able to connect to the websocket, but no matter what I did, when I tried to connect with my own code, I kept getting the error message that the websocket connection failed
Long story short, They changed an apache configuration that allowed connecting to the websocket via a proxy.
In the old version, apache config was:
ProxyPass /socket/ ws://localhost:33015/ retry=10
ProxyPass /socket ws://localhost:33015/ retry=10
In the new version, apache config was changed to:
ProxyPass /socket/ ws://localhost:33015/ retry=10
By bad luck, I was trying to connect to ws://localhost/socket and not to ws://localhost/socket/. As a result, proxy was not found, and connection returned an error.
Moral of the story: Make sure that you are trying to connect to a websocket url that exists.
For me, the solution was to change the URL from ws:// to wss://. This is because the server I was connecting to had updated its security, and now only accepted wss.

how to embed nodejs application on client website?

firstly sorry for not standard English. : D
I have a chat application using nodejs, expresss finished running on port 3000. So I want to embed in website application clients, then how?
I had to use ajax load, but can not be:
jQuery.ajax({
type:"GET",
url:"http://localhost:3000/client/",
success: function (data){
jQuery('body').append(data);
}
});
Since you are using socket.io at server side then you can get its reference at the client using below line (jquery required):
$.getScript(host+'socket.io/socket.io.js', function()
{
var clientSocket = io.connect(host);
// ... do other stuff with your socket
});
Where host is your server host name e.g. http://192.168.1.5:3000/ where your nodejs application is deployed.
For more information see here for more client - server communication exposed events.
try the example from http://book.mixu.net/node/ch3.html (it uses long-polling) once done with it use socket.io

Generating socket.io at Server side as Rest request

There is a way to manage the socket.io creation at Server Side?, Currently, I couldn't found any doc, Only found in relation with the socket is created per request from a client "io.connect(server)".
The current flow work OK:
Set Socket.io (at Node.js) at SERVER:PORT
Client connect to SERVER
using io.connect(SERVER:PORT)
I wonder if it is possible ? Trying to do:
Set Socket.io (at Node.js) at SERVER:PORT
Recieved a POST (REST) - Server side
Create/Open Socket.io a server side.
At response of Post send the id?
the clien open a socke.io
Sent to client socket.id to client as
So Far, looking in deep on the code and doc, I found that socket.io support namespaces, so I used this in order to manage client connection id.
at server.js
var app = express();
var server = require('http').createServer(app),
io = require('socket.io').listen(server,{ log: false });
// Rest New Process
function generateNameSpaceWs (responce, request) {
io.of("/" + id).on('connection', handler);
response.send(id);
}
app.post("/newWS", function (res, req) {
return generateNameSpaceWs(res, req);
}
at Client.js
function makeWS(){
var ws, c = new XMLHttpRequest();
c.open("GET", url, false);
c.send();
if (c.status == 200){
id = JSON.parse(c.responseText);
ws = new io.connect("server/" + id)
}
So far you are doing right, if I understand your question correctly, you are trying to authenticate connection via POST, so that user can only connect to server via socket if server responds to ID. This is a roundabout way. Use the socket instead of POST.
Socket server has to be running already, and accepts connection via io.sockets.on('connection'), at server you can choose whether to accept it or reject it ,do socket.disconnect('unauthorized') to close connection from server.
I would you suggest you do this :
Set Socket.io (at Node.js) at SERVER:PORT
Client connect to SERVER using io.connect(SERVER:PORT)
Send what you are sending in POST over socket.
Authenticate/Process on io.sockets.on('connection', function(socket) at server.
Close socket if unathorized.
Send back ID data to client.
This doesn't seem possible -- while the official documentation for socket.io is lacking, the documentation for the net module indicates that the only way to create a socket is to initiate it server side.
However, you can still achieve the desired effect by creating an id for the socket on the server to associate with the socket. That is,
Set Socket.io (at Node.js) at SERVER:PORT
Recieved POST (REST) - Server side
Create id (Note:This could be done before step 2)
At response of Post send the id!
Client connect to SERVER
using io.connect(SERVER:PORT)
The client sends the id to the server using something like
socket.emit("set_id",id)
The server recieves the id and associates it with the socket using something like
socket.on("set_id",function(id){
socket.set("id",id)
}
Now you can reference the socket using the id that you created!
Good luck!

Get a static request to push some data to clients using Node.js and Socket.io

I'm new to Node.js, and I've been playing with the "chat" example provided with the Socket.io install package. Is shows in a few lines of code how you can push some data to several clients (browsers) in a push-fashion (no pulling).
Here is the code on the server side : http://pastie.org/1537175
I get how you can send a message to a client with client.broadcast(msg), but I don't get how you can do it outside of the
io.on('connection', function(client){
... }
loop
I would like to invoke a client.broadcast(msg) when someone hits a particular url (like '/test.html'), see line #32. The device asking for the '/test.html' is not a typical "ajax-enabled" browser, but a mere text-based browser, so I cannot initialize an asynchronous request with the server. Any idea?
Thank you.
you can use .broadcast on your io object
case '/test.html':
io.broadcast('test'); // This is where I would like to invoke a client.broadcast(msg);
break;

Resources