How to connect to a nodejs socket server? - javascript

I am new to node JS and I am trying to create a real time application that consists of a node JS server with socket.io and a unity application that can connect to it
I created the server with the sockets in the below code :
const express = require('express');
const http = require('http');
const app = express();
const port = process.env.PORT || 9000;
const server = http.Server(app);
const io = require('socket.io')(server);
io.on('connection',(socket) => {
console.log('A user connected');
socket.on('disconnect', () => {
console.log('user disconnected');
});
})
app.get('/',(req,res) =>{
res.json({worked : 'worked'});
});
server.listen(port,() => console.log(`Listening on localhost ${port}`));
I can connect to the socket server via the nodejs client files using socket.io-client
<script>
const socket = io('http://localhost:9000');
socket.on('message',(message) => console.log(message));
</script>
But the problem is whenever I try to connect from a different client I don't receive anything in the console.
I tried to use Smart Web Socket client to debug what's happening but whenever I connect (try to)
this happens
Any help would be much appreciated and thanks in advance

So if anyone stumbles in this thread I was able to fix the problem by installing the latest version of socket.io (^3.1.0) and allowing the EIO3 connections

Related

socket.io client not firing events on socket io server

I have built a backend and wanted to test it with some front-end code but for whatever reason, it is just not firing the events on the server. I dont get the "on connect" event triggered. I already downgrade the backend to a version similar to my testing script but still all the server shows, are logs like this.
[22/Oct/2021:14:06:21 +0000] "GET /socket.io/?EIO=4&transport=polling&t=NoeKlFT&b64=1 HTTP/1.1" 404 149 "-" "node-XMLHttpRequest"
I am using socket io for server and client version 3.1.2
Here is the backend code snippet
const dotenv = require("dotenv").config();
const express = require("express");
const app = express();
const server = require("http").createServer(app);
const io = require("socket.io")(server);
const morgan = require("morgan");
const cors = require("cors");
const config = require("./src/config/general");
const exchangeController = new ExchangeController(io); // I want to pass in the IO obejct to be able to deal with all the event stuff in another file besides the apps entry point file.
Here is the part where I want the IO object to be available and work with the events from there
class ExchangeController {
constructor(io) {
this.io = io;
this.exchangeService = new ExchangeService();
this.router = express.Router();
this.initRoutes();
this.io.on("connection", (socket) => {
console.log("incoming socket connection"); //gets never logged to console when connecting frontend
//do further stuff (deleted for post)
});
});
}
This is the frontend script for testing the connection
//client.js
const io = require('socket.io-client');
const socket = io("mysecreturl") //also tried localhost instead of deployed app url no difference
// Add a connect listener
socket.on('connect', function (socket) {
console.log('Connected!');
});
I really tried for way too long now without getting any results. I hope you guys can guide me on the right path again.
Cheers

Why doesn't console.log print to the CLI?

I'm following a YouTube tutorial on NodeJs, and for some reason my console.log commands unexpectedly stopped working. Here is the sample code from the tutorial as I've typed it:
const http = require('http');
const server = http.createServer();
server.on('connection', (socket) => {
console.log('New connection')
});
server.listen(3000);
console.log('Listening on port 3000...');
After saving I try using node and nodejs
node app.js
nodejs app.js
but they print nothing.

How can I connect to an established server (NOT localhost) with node.js & socket.io?

I am very new to web servers / node.js / socket.io and I'm trying to make a very simple website just to learn how to connect 2 people. All of the tutorials I've found teach you how to run your app on localhost, but I want to run it on a server so everyone can access it.
I found this hosting website - Zeit-Now - and managed to put my website online. My website works just fine on localhost, but I can't get it to work when i put it online. I think the problem is in these 2 lines in my code, where the '???' are.
index.html:
<!DOCTYPE html>
<html>
<head>
<title>A2</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.2.0/socket.io.js"></script>
</head>
<body>
<input id="sendMsg" type="text" placeholder="TYPE TO SEND">
<input id="receiveMsg" type="text" placeholder="RECEIVE HERE">
<button id="sendBtn">Send</button>
<script>
var socket = io.connect('https://web-socket-2.quaei.now.sh/');
var sendMsg = document.getElementById('sendMsg');
var receiveMsg = document.getElementById('receiveMsg');
var sendBtn = document.getElementById('sendBtn');
// Emit events
sendBtn.addEventListener('click', () => {
socket.emit('chat', {
message: sendMsg.value
});
});
// Listen for events
socket.on('chat', data => {
receiveMsg.value = data.message;
});
</script>
</body>
</html>
index.js:
const express = require('express');
const app = express();
const server = require('http').Server(app);
const io = require('socket.io')(server);
app.use(express.static('public'));
io.on('connection', socket => {
console.log('Connection! ->', socket.id);
socket.on('chat', data => {
io.sockets.emit('chat', data);
});
});
I've also tried:
var socket = io.connect(https://web-socket-2.quaei.now.sh/);
and
var server = app.listen(80, https://web-socket-2.quaei.now.sh/);
I expect my website to read what is written in the first input field and output it in the second one when clicked send (which works fine on localhost), but it doesn't work when I put it online with Zeit-Now.
Edit:
now.json:
{
"version": 2,
"name": "web-socket-2",
"builds": [{
"src": "public/**/*",
"use": "#now/static"
},
{
"src": "*.js",
"use": "#now/node"
}
],
"routes": [{
"src": "/",
"dest": "public/index.html"
}]
}
I have a #websocket-2 folder with now.json, index.js and public folder. In public folder I have index.html.
How can I make it work on this website: https://web-socket-2.quaei.now.sh/ ?
I guess the problem you face at the moment is that you want to run the server directly on the website. But it's need to be run by node like this:
node index.js.
Therefore you need access to the server like some ssh access and then start it there with the command named above. Based on the logs, I can say that the client can't find the server.
You also need to make sure that it resolves to the right path.
Start it with app.listen(80) and then try to connect to
https://web-socket-2.quaei.now.sh:80
try this
const app = express();
const server = http.createServer(app);
const io = socketio(server);
server.listen(80, '0.0.0.0');
Make sure your server has websockets enabled. (It does not actually need websockets, but it will use it if possible for better transport)
Reading about zeit.co I can see they dont support websockets, not sure if they support sucket either. I would recommend you hitting them up with email to confirm this if code below does not help you.
To run connection on client side, after you have installed socket.io-client or after you have included script in header, which you have.
You simply connect using io.connect('SERVER URL') which will return your socket connection instance. (no need to pass server if running on same server)
const socket = io.connect('http://youserver.com');
// You can listen to conenct and disconnect to track your connection
socket.on('connect', socket => {
console.log('Connected', socket.id);
});
Thats it on client side.
On server side, you need to pass server to your socket.io module
const io = require('socket.io')(server);
// You can listen to your socket connecting through connect and disconnect
io.on('connect', (socket) => {
console.log('socket connected', socket);
});
You can track your errors on client side using 'error' event, and make sure to check your console to see the logs about the connection.
In case you are using express server, and socket is raising 404 errors in console, make sure you initiate server using http instead of express.
const app = express();
const server = require('http').Server(app);
const io = require('socket.io')(server);
// your socket and routes
server.listen(process.env.PORT || 3500, () => {
console.log(`Localhost working on ${process.env.PORT || 3500}`);
}

socket.io with express slows down after amount of request from react client

I have built a React app that is connected to a local running express node server with socket.io. Everything works fine but after a few hours of 100+ sending requests, and listening to those changes from the local server to the client it starts to slow down and won't work as efficiently until I reload the client window sessions.
I have a very difficult time troubleshooting this. Do you think it has something to do with my node server setup, or is it something with my client? Or maybe it's hardware issues? One thing I notice is that how my client keeps connecting to socket.io from the console.
const express = require('express')
const http = require('http')
const socketIO = require('socket.io')
// localhost port
const port = 4001
const app = express()
// server instance
const server = http.createServer(app)
// creates socket
const io = socketIO(server)
io.on('connection', socket => {
socket.on('change view', (view) => {
console.log('view changed to: ', view)
io.sockets.emit('change view', view)
})
})
server.listen(port, () => console.log(`Listening on port ${port}`));
React app client side:
componentDidMount() {
const socket = socketIOClient(this.state.endpoint);
socket.on('change view', (col) => {
callAfunctionThatDoesSomething(col);
})
};
When I send changes to the server
send = () => {
const socket = socketIOClient(this.state.endpoint);
socket.emit('change view', this.state.view);
}
Any ideas?
You are connecting to socket.io two times. First at componentDidMount and second, when calling send(). Which is not recommended.
You should connect to socket one time. You can connect in componentDidMount method of a component. But if you want to use socket in multiple component. This will also connect to socket multiple time.
I will say you connect to socket one time when registering routes or your whole app. I created a sample app before. You can check it.
https://github.com/vkasraj/random.ly

How to redirect app's data stream to browser in real time?

My node app can read stream from kafka producer and console.log it to terminal in real time. But I would like to update it in my web app the same way (real time). How can I implement it?
I start my app with 'node index.js' command (or npm start).
index.js:
'use strict';
var express = require('express'),
app = express(),
server,
data = [];
...
consumer.on('message', function (message) {
console.log(message);
data.push(message);
//global.location.reload();
});
...
app.get('/', function(req, res){
res.send(data);
});
server = app.listen(3002, function(){
console.log('Listening on port 3002');
});
I think, that I need modify res.send(data) or add some code to on('message') event.
You should keep connection between client and server.
Try this socket.io package to update message in realtime.

Categories