Chat with another pc with react chat-app and socket.io - node.js

I followed a youtube tutorial on making a chat app with react js and socket.io. It is complete and works perfectly, but only on the pc, the project is running on. What I need is the application to chat with another pc the project is working on, it could be on the same network, for starters. The front-end is separate and is made with react js.
I tried adding a dummy IP to where I specify the port it will run on, but didn't work.
Any ideas? What am I missing here?
Here's the code to the server.js which is in plain node js:
const port = 5000 || '0.0.0.0' <--- Ignore the dummy IP kindly, didn't work, thought it was worth a try
const io = require('socket.io')(port)
io.on('connection', socket => {
const id = socket.handshake.query.id
socket.join(id)
console.log("Listening at " + port)
socket.on('send-message', ({ recipients, text }) => {
recipients.forEach(recipient => {
const newRecipients = recipients.filter(r => r !== recipient)
newRecipients.push(id)
socket.broadcast.to(recipient).emit('receive-message', {
recipients: newRecipients, sender: id, text
})
})
})
})

I'd recommend you look into deploying your chat app on something like Heroku or Firebase, which will provide you a 3rd-party non-localhost link that other PCs and users can go to in order to access your chat app.
Alternatively, you can use something like https://github.com/localtunnel/localtunnel to have other PCs access your localhost

Related

Socket.io client in NodeJS

I want to build a microservice infrastructure with nodejs services and a master service, the communication between these services should happen via socket.io, i've setup my socket.io server, but their browser client (socket.io-client) is not working in nodejs (i guess it uses some browser only APIs). Is there a way to create a nodejs socket.io (NOT WEBSOCKETS) client?
EDIT
My client side code:
import { io } from "socket.io-client";
const socket = io("127.0.0.1:3000");
socket.on("connect", () => {
console.log(socket.id);
});
socket.on("disconnect", () => {
console.log(socket.id);
});
My server side code:
import { Server } from "socket.io";
const io = new Server();
io.on("connection", (socket) => {
console.log(socket)
});
io.listen(3000);
Both are written in typescript, the package versions are:
socket.io: ^4.4.0
socket.io-client: ^4.4.0
The Problem is, that i don't get any logs in my console, so i think there is something wrong with client, because socket.io does not mention node in there client side compatiblity graph.
The problem is that you have to pass a valid URL here:
const socket = io("127.0.0.1:3000");
I have no idea why socket.io doesn't give you an error, but if you change that to:
const socket = io("http://127.0.0.1:3000");
Then, it will work.
If you set DEBUG=socket.io-client in your environment, it won't show you an error, but it will show you that it's trying to connect to:
undefined//127.0.0.1:3000
which would give you a clue, I guess.
If you set DEBUG=* in your environment, you will get a lot more debug info (so much that it's a bit hard to sort through).
Set Logging and Debugging Socket.io for more info.

Frontend to backend request seems to be wrong

Hi I am trying to deploy a simple React + Node app to a remote server. Backend started with pm2 and seems ok, frontend works with nginx, but when I try to get data from the db, console sends message
GET http://localhost:8080/v1/names net :: ERR_CONNECTION_REFUSED xhr.js: 177
Not too sure if I need to replace request url with the server IP instead of localhost.
Any help is greatly appreciated.
Yes, you should change all your request from localhost to your deployed address, I would also propose you take a look at .env Files to do it. Node.js Everywhere with Environment Variables!.
usually, you should use .env files to automatically choose the good address when deployed and when coding locally. have a nice day.
example of code with a .env file from the back with mongoose.
mongoose
.connect(
`mongodb+srv://${process.env.DB_USER}:${process.env.DB_PASSWORD}#cluster0.qvs4c.mongodb.net/${process.env.DB_NAME}?retryWrites=true&w=majority`
)
.then(() => {
app.set("port", process.env.PORT || 5000);
app.listen(app.get("port"), function () {
console.log("Node app is running on port", app.get("port"));
});
})
.catch((err) => {
console.log(err);
});
example of my .env File.
DB_USER=thatsmydbuser
DB_PASSWORD=thatsmypassword123!
DB_NAME=thatsmydbname

Node.js, Express.js, Angular.js: Hosting my own API

I am new to coding and I have a question about a small app that I created with angular.js that makes a post request to another express.js app.
It's a simple parentheses balance checker, you can find the whole code here:
https://github.com/OGsoundFX/parentheseschecker
The FrontEnd-Refactored folder contains the Angular.js app and the APItesting contains the express.js API.
The app is working, but I have only been using it locally. The API runs on localhost:3000 and the app on localhost:8080
But what if I want to make it public? How would I go about it? I don't really know where to start.
Where to host a node.js of express.js app. I read about AWS, would that be good, or are there better services?
I have a Wordpress website hosted on https://www.mddhosting.com/ but that wouldn't work, right?
My Angular app is calling the api locally at the moment, so I will probably have to change the API link that it is fetching:
ApiService.js
function ApiService($http) {
API = '//localhost:3000/parentheses';
this.getUser = (entry) => {
return $http
.post(API, { string: entry} )
.then(function (response) {
return response.data;
}, function (reason) {
// error
})
};
};
angular
.module('app')
.service('ApiService', ApiService);
In my API server.js
const http = require('http');
const app = require('./app')
const port = process.env.PORT || 3000;
const server = http.createServer(app);
server.listen(port);
I will definitely have to change API = '//localhost:3000/parentheses'; in my AngularJS app, but should I change const port = process.env.PORT || 3000; ?
I just need a little push start to help me clear some confusion.
Thanks!
Ensure you use application-level environment variables For example: To define the BASE_URL of your site for development and production separately. Doing so you don't have to make any configuration changes when you go live, it is a one-time process.
And if you are looking for free hosting services for pet projects Heroku is good and if you really want to make site go live for the end-users you may go for AWS EC2 instance or Heroku paid service both are good.

App using socket.io and Node.js works locally but not deployed to heroku

Tried other solutions I could find such as adding process.env.PORT and also looked at heroku's guide on socket.io.
The Phaser.io game my group is making works perfectly locally, however when we deploy to heroku there is a bug where only the first player connected will see the other players, and only for a brief moment as well. After that short period, the players freeze.
My question is, does anyone have any clue what could potentially be causing the issue? Is it something wrong with our implementation of socket.io?
Thank you in advance for your help. Extremely confused as to what is causing this issue.
Here is a deployed version: https://death-road-to-toronto.herokuapp.com/
Here is the repo if you'd like: https://github.com/Road-To-Capstone/CapstoneMultiplayer/
Here are the code snippets relevant to socket and express
Index.js
const config = require('./config');
const express = require('express');
const socketio = require('socket.io');
const http = require('http');
const app = express();
const server = http.createServer(app);
const io = socketio(server);
app.use('/', express.static(config.publicDir));
//-socket
const players = require('./players.js');
const missiles = require('./missiles.js');
const zombies = require('./zombies.js');
io.on('connection', socket => {
-------
});
//=socket
server.listen(process.env.PORT || config.port, () => {
console.log(`Listening on ${config.port}`);
});
//creating new zombie id
function newZombieId() {
let id = new Date();
return id.getTime();
}
config.js
const path = require('path');
module.exports = {
port: 3000,
publicDir: path.join(__dirname, '../public'),
game: {
start: {
x: 400,
y: 400
}
}
}
EDIT1 : I made a funny discovery while playing around with socket.io and heroku. So if I connect with another computer to the deployed version on heroku, then click on console (just to freeze the game). Anyone at that point can join and everything works perfectly, just like in the local copy.
Does anyone know why? If not what can I do as a work around? Perhaps implement a lobby system and allow all players to join and start at the same time?
Solved my problem! Going to leave my question and the solution here for prosperity, incase other people want to implement a multiplayer game using Phaser and socket.io on Heroku and also run into issues.
We added this to the index.html file </script type ="text/javascript" src="/socket.io/socket.io.js"> </script> which allows heroku to access the socket library.
It actually wasn't a setup issue with socket.io, it was our logic. When a player detects movement it instantly tries to socket.broadcast that a player moved. However, when other players first connect, they don't have time to retrieve all the players information from the server side. Thus the broadcast would cause an error where "player" is undefined. Adding a conditional statement fixed our issue.
The code in it's entirety is going to be left on github if you want to investigate further.

heroku app crashes with socket.io

The application, an API server meant to communicate with a Unity client was working just fine, until I added sockets. Manually testing socket.io using the chrome extension socket.io tester demonstrated that it is working just great on my local machine. Now that I've deployed it to heroku, it doesn't work. It crashes right off.
Typically, answers to this issue are all about the PORT not being set correctly, but in this case I have set the port to process.env.PORT, so there shouldn't be any problems with that. My app was working just fine until I added socket.io.
Here is my basic server file:
import express from "express"
import mongoose from "mongoose"
import http from "http"
import config from "./config/index.js"
mongoose.Promise = global.Promise
// mongo
mongoose.connect(config.mongo.uri)
mongoose.connection.on("error", function(err) {
console.error("MongoDB services error: " + err)
})
// server
let app = express()
let server = http.createServer(app)
let socketio = require("socket.io")(server)
require("./socketio").default(socketio)
require("./express").default(app)
require("./api").default(app)
// start
server.listen(config.port, function () {
console.log("Listening on port: " + config.port)
})
export default app
Is there anything here to imply why the app may be crashing?
So for anyone who might also be having trouble with Heroku in this way. It turns out that I had my config file with the proper port setting listed in my .gitignore file. (I don't know how it got there!) I wasn't paying attention to the logs when the app was starting up so I was missing the log that it the config file was missing. I was impressed by how Heroku's staff was able to point that out.

Resources