Socket IO server being broken? - socket.io

I can't tell if this is a bug on my side or not, but I just can't figure out why this is not working.
Running a basic nodejs server and on a test page on nextjs, socket io is working perfectly fine. However, when I'm using it on my actual page, it does constant polling and never starts the ws connection, and the events don't work. The polling does have an appropriate response, with "upgrades":["websocket"] and all.
And, it seems that after the constant polling on that broken page starts, then the test page also starts doing it and doesn't work unless I restart my nodejs server. If I navigate to the broken page from the test page through nextjs, it also works, but a refresh then breaks it again. Any reason why this is so?

You can do this with this script. This is my personal working script for socket IO chat app.
Backend Server
require("dotenv").config();
const port = process.env.SOCKET_PORT || 3000;
const main_server_url = process.env.SERVER_URL;
var express = require("express");
var app = express();
var server = app.listen(port);
var connectionOptions = {
"force new connection": true,
"reconnection": true,
"reconnectionDelay": 2000, //starts with 2 secs delay, then 4, 6, 8, until 60 where it stays forever until it reconnects
"reconnectionDelayMax": 60000, //1 minute maximum delay between connections
"reconnectionAttempts": "Infinity", //to prevent dead clients, having the user to having to manually reconnect after a server restart.
"timeout": 10000, //before connect_error and connect_timeout are emitted.
"transports": ["websocket"] //forces the transport to be only websocket. Server needs to be setup as well/
}
var io = require("socket.io").listen(server, connectionOptions);
var axios = require("axios");
var users = [];
var connections = [];
console.log("Server connected done");
io.sockets.on("connection", function (socket) {
var server_url = main_server_url;
console.log(server_url);
console.log(people);
connections.push(socket);
console.log("Connected : total connections are " + connections.length);
// rest of events of socket
});
Front End JS for load IO for client
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.3.0/socket.io.js"></script>
<script type="text/javascript">
var base_url = YOUR_BASE_URL;
var port = YOUR_SOCKET_PORT;
var socket_port_url = base_url + ":" + port;
var socket = io(socket_port_url);
socket.on('done', (data) => {
console.log(data);
});
</script>

Related

Sending data received from one socket.io server to a web socket client

I'm starting to use socket.io and I have a problem that I can't solve so far
I have two nodejs running, one is the socket.io data server and the other one is going to interact with web clients
I need to get data from the server and send it to my web clients, the problem is I can't emit data to the clients outside the 'on connect'
I think is better to explain it with a simple example
const socket = require('socket.io-client')('http://localhost:12000');
const SocketIO = require('socket.io');
const app = require('../app');
const server = http.createServer(app);
server.listen(port);
// client socket, this is a regular message from
// the server running on port 12000, it works
socket.on('msg_from_server', data => {
console.log(data);
});
// server socket
const io = SocketIO(server);
io.on('connection', (s) => {
// this works
s.emit('msg_to_client', {data: 'xxxx'})
// this doesn't works
socket.on('msg_from_server', data => {
console.log(data);
});
});
socket client for server on port 12000 and socket from io.on('connection', (socket) both are different. But you are mixing them both.Do something like this:
const Socket_12000 = require('socket.io-client')('http://localhost:12000');
const SocketIO = require('socket.io');
const app = require('../app');
const server = http.createServer(app);
server.listen(port);
// client socket
socket.on('msg_from_server', data => {
console.log(data);
});
// server socket
const io = SocketIO(server);
io.on('connection', (socket) => {
// this works
socket.emit('msg_to_client', {data: 'xxxx'})
// this doesn't works
Socket_12000.on('msg_from_server', data => {
console.log(data);
});
});
I have created a basic gist depicting the problem/solution please commant if you are looking something else.
https://gist.github.com/sandeepp2016/bb1946bcbeb2f11d57bc3aa2e44c158e

how socket.io get downloaded from my server even I didn't assign any router for it

how nodejs handle /socket/socket.io.js/ request even I don't assigned any router for it
this is script tag in html
<script src="/socket.io/socket.io.js"></script>
and this is my simple nodejs server
var express = require('express');
var path = require('path');
var app = express();
var server = require('http').Server(app);
var io = require('socket.io')(server);
var port = 8080;
app.use(express.static(path.join(__dirname, "public")));
server.listen(port, function() {
console.log("Listening on port " + port);
});
it should get this error : 404 page not found
but it correctly load it
It's the default behaviour of socket.io server .
take a look here: https://socket.io/docs/server-api/
it's called "serveClient" and it's set to true as default .

React Native Websocket Android not connecting to server

I'm trying to use React Native's built in Websocket support. I have this code:
var hostname = "192.168.X.XXX";
var port = "4567";
const webSocket = new WebSocket("ws://" + hostname + ":" + port + "/chat");
and I have this:
componentWillMount: function(){
console.log("MOUNTING CHAT COMPONENT");
webSocket.onopen = function(){
console.log("binding to chat room");
bindToChatRoom();
setTimeout(keepWebSocketOpen, 30000);
ws_connected = true;
};
webSocket.onmessage = function (msg) {
this.handleMsg(msg);
};
webSocket.onclose = function () {
console.log("WebSocket connection closed");
ws_connected = false;
};
webSocket.onerror = function (e){
//add some error handling -> DO THIS
console.log(e.message);
};
},
I'm running a local server using sparkjava, with this:
webSocket("/chat", ChatWebSocketHandler.class);
etc. I've tested the server, and I can connect to it (and send messages) both through both my web browser on my laptop AND on my phone with URL 192.168.x.xxx:4567/chat . However, when I run the react native app, I never see the console message "binding to chat room". Am I missing something? How come this websocket never opens?
Just want to note, I also tried connecting here:
ws://echo.websocket.org
which is described here:
http://www.websocket.org/echo.html
This is a known working websocket, so I know it's purely a react native issue...
Turns out that I had the line of code
const webSocket = new WebSocket("ws://echo.websocket.org");
in the wrong place. If you move it into componentWillMount, it works just fine.

Node app; Call server function from Client

I can't seem to call a server function from my client using either socket.io or an ajax call. Any help would be appreciated. For socket.io, I was trying something like this:
server (no error is being thrown, only I never see the console.log):
var app = express();
var server = require('http').Server(app);
var io = require('socket.io')(server);
var socket = io.sockets.on('connection', function(socket) {});
socket.on('admin-refresh', function() {
console.log("*** Admin refresh ***");
});
client (yes I'm including all necessary files, no error is being thrown on client side nor server):
$('document').ready(function() {
var socket = io();
$('#refresh').click(function() {
console.log('refresh clicked..');
io.emit('admin-refresh');
});
});
I don't need any data to be passed, I just want to alert the server to call a function. So perhaps an ajax call would be easier? How would I set up the server to listen for calls?
Why do you have an empty connection callback..? Look at the docs again.
var app = express();
var server = require('http').Server(app);
var io = require('socket.io')(server);
io.on('connection', function(socket) {
socket.on('admin-refresh', function() {
console.log("*** Admin refresh ***");
});
});

Socket.io connection url?

I have the current setup:
Nodejs Proxy (running http-reverse-proxy) running on port 80.
Rails server running on port 3000
Nodejs web server running on port 8888
So any request starting with /nodejs/ will be redirected to nodejs web server on 8888.
Anything else will be redirected to the rails server on port 3000.
Currently Socket.io requires a connection url for io.connect.
Note that /nodejs/socket.io/socket.io.js is valid and returns the required socket.io client js library.
However, I am not able to specify connection_url to /nodejs/ on my server.
I have tried http://myapp.com/nodejs and other variants but I am still getting a 404 error with the following url http://myapp/socket.io/1/?t=1331851089106
Is it possible to tell io.connect to prefix each connection url with /nodejs/ ?
As of Socket.io version 1, resource has been replaced by path. Use :
var socket = io('http://localhost', {path: '/nodejs/socket.io'});
See: http://blog.seafuj.com/migrating-to-socketio-1-0
you can specify resource like this:
var socket = io.connect('http://localhost', {resource: 'nodejs'});
by default resource = "socket.io"
If you are using express with nodejs:
Server side:
var io = require('socket.io')(server, {path: '/octagon/socket.io'});
then
io.on('connection', function(socket) {
console.log('a user connected, id ' + socket.id);
socket.on('disconnect', function() {
console.log('a user disconnected, id ' + socket.id);
})
})
socket.on('publish message ' + clientId, function(msg) {
console.log('got message')
})
Client side:
var socket = io('https://dev.octagon.com:8443', {path: '/octagon/socket.io'})
then
socket.emit('publish message ' + clientId, msg)
I use below approach to achieve this goal:
client side:
var socket = io.connect('http://localhost:8183/?clientId='+clientId,{"force new connection":true});
server side:
var io = require('socket.io').listen(server);
io.sockets.on('connection', function(socket) {
console.log("url"+socket.handshake.url);
clientId=socket.handshake.query.clientId;
console.log("connected clientId:"+clientId);
});
reference:https://github.com/LearnBoost/socket.io/wiki/Authorizing#global-authorization
If you are serving your app with express, then maybe you can check this out. Remember express uses http to serve your application.
const express = require('express'),
http = require('http'),
socketIo = require('socket.io'),
app = express()
var server = http.createServer(app);
var io = socketIo(server);
io.on('connection', (socket)=>{
// run your code here
})
server.listen(process.env.PORT, ()=> {
console.log('chat-app inintated succesfully')
})

Resources