Using Socket.io in React Native and Hapi Server - node.js

I'm trying to setup a simple socket io system for my React Native App (using Expo) to send messages back and forth from my Node Hapi server. Right now I have a print out on the Server to print when a connection is established however it is never printed. My Node server is hosted on a Amazon AMI instance using port 3030. Here are some code snippets. Any idea why the connection is not being made?
Server Socket IO Code:
const io = require('socket.io')(server.listener);
io.on('connection', (socket) => {
console.log('Socket connection established.');
socket.emit('connection', true);
});
Client Socket IO Code:
const io = require('socket.io-client');
componentDidMount() {
this.socket = io('http://{my_aws_instance_public_ip}:3030', {
transports: ['websocket']
});
this.socket.on('connect_error', (err) => {
console.log(err)
});
}

Related

Socket.IO Error 400 when connecting to server, or never connects

I'm working on chat app, I have Android version made in Flutter, where Socket.IO works fine. Now I'm making web app of this chat app. But when the app tries to connect to server, the error is thrown:
WebSocket connection to 'ws://localhost:3000/socket.io/?EIO=4&transport=websocket' failed: Error during WebSocket handshake: Unexpected response code: 400
Here is client code (I'm using React):
console.log("Connecting to websocket...");
this.socket = io(this.serverUrl(), {
transports: ["websocket"],
autoConnect: false
});
this.socket.on("connection", (data) => {
console.log("Connected webscoket.");
this.socket.emit("join", { token: this.token });
});
this.socket.connect();
Here is server code (Node.js), (The code is not complete, of course):
const express = require("express");
const app = express();
const http = require("http").createServer(app);
const port = process.env.PORT;
const io = require("socket.io")(http);
http.listen(port, () => {
console.info("Server is running on port " + port);
});
io.on("connection", async (socket) => {
console.log("Connected socket.io client " + socket.id);
});
socket.on("disconnect", async (reason) => {
console.log("Socket disconnected");
});
I also tried to add origins like this:
const io = require("socket.io")(http, {
origins: ["http://localhost:3001"]
});
Then the error is not there, but it never connects, and server console output looks like this:
Server is running on port 3000
Connected to database
Connected socket.io client QkoLREixPEyNglK7AAAA
Connected socket.io client QkoLREixPEyNglK7AAAA
Socket disconnected
Connected socket.io client C-j2N_Bvz8QDEQKUAAAB
Connected socket.io client C-j2N_Bvz8QDEQKUAAAB
Socket disconnected
Connected socket.io client 4Q6vxnNJb0gR-rVtAAAC
Connected socket.io client 4Q6vxnNJb0gR-rVtAAAC
Socket disconnected
Connected socket.io client g7MMXfwBuqjtS31_AAAD
Connected socket.io client g7MMXfwBuqjtS31_AAAD
Socket disconnected
Connected socket.io client NIquCegqW9yygXkIAAAE
Connected socket.io client NIquCegqW9yygXkIAAAE
...
Also the Android app stop working this way.
Thank you for all your answers.

Node.js Socket.io client on Flask socket.IO server

I'm trying to connect a Node.js Socket.IO client to a Python/Flask Socket.IO server.
On the server (Raspberry Pi) runs this project: Pi-GPIO-Server. This project already has a built-in website which is a socket.io client to access the pins of the Raspberry Pi.
The whole project works well.
Now I'd like to access the socket.io connection from a Node.JS client.
On the server side, I've updated the IP and port of the server to:
if __name__ == '__main__':
socketio.run(app, host="192.168.0.8", port=5000)
On the client side my implementation is (as stated in the documentation of the project)
var io = require('socket.io-client');
var socket = io.connect('http://192.168.0.8:5000', {path: '/', transports: ['websocket']});
socket.on( 'connect', (socket) => {
console.log('Connected: ');
console.log(socket);
});
socket.on( 'pins:list', (list) => {
console.log('List of Pins: ');
console.log(list);
});
Any ideas, why I cannot get a connection?
Is there a limitation of clients in the Flask server? Any special command to send?
Is there a possibility to debug the connection?
#Christoph Please use the below code you should be able to connect...I have Flash server running and Nodejs as a client, It is working fine for me!!!
In my case i am running both server and client in same machine so i used localhost in place of IP address
const socket = require('socket.io-client')('http://192.168.0.8:5000', {
reconnection: true,
reconnectionDelay: 10000
});
socket.on('connect', (data) => {
console.log('Connected to Socket');
});
socket.on('event_name', (data) => {
console.log("-----------------received event data from python flask srver");
});
//either 'io server disconnect' or 'io client disconnect'
socket.on('disconnect', (reason) => {
console.log("client disconnected");
if (reason === 'io server disconnect') {
// the disconnection was initiated by the server, you need to reconnect manually
console.log("server disconnected the client, trying to reconnect");
socket.connect();
}else{
console.log("trying to reconnect agan with server");
}
// else the socket will automatically try to reconnect
});
socket.on('error', (error) => {
console.log(error);
});

Heroku Deployment of NodeJS and ReactJS

I want to deploy 2 seperate projects on same Heroku machine. I have React application for frontend and nodejs server in the back.
They are connected over localhost in my machine with the following structure. In the react side, with following client structure, I can see the Connected to : localhost:5000 is printed. :
import openSocket from 'socket.io-client';
socket = openSocket("http://localhost:5000");
socket.on("connect", () => {
console.log("Connected to : http://localhost:5000");
});
Node Side is like following and Client connected is printed in my local machine:
const server = require('http').createServer();
const io = require('socket.io')(server);
server.listen(5000, function(err) {
if (err) throw err;
console.log('Server Listening on port:', 5000);
});
io.on('connection', (client) => {
console.log("Client connected!");
}
After that I deployed my projects on 2 different clusters in Heroku.
NodeJS works on https://<herokuname>.herokuapp.com/
So I wonder that to write in the openSocket method in React side in order to connect socketio connection on that domain. I tried followings but none of them worked :
https://<herokuname>.herokuapp.com:5000/socket.io/?EIO=4&transport=websocket
https://<herokuname>.herokuapp.com/socket.io/?EIO=4&transport=websocket
ws://<herokuname>.herokuapp.com:5000/socket.io/?EIO=4&transport=websocket
ws://<herokuname>.herokuapp.com/socket.io/?EIO=4&transport=websocket
You have to bind your server to a specific process.env.PORT provided to you by Heroku for web dynos.
const server = require('http').createServer();
const io = require('socket.io')(server);
const PORT = process.env.PORT || 5000;
server.listen(PORT, function(err) {
if (err) throw err;
console.log('Server Listening on port:', PORT);
});
io.on('connection', (client) => {
console.log("Client connected!");
}
Once that's working, you should be able to just hook up to the root heroku server URL from your client.
import openSocket from 'socket.io-client';
const url = "https://<herokuname>.herokuapp.com"
socket = openSocket(url);
socket.on("connect", () => {
console.log("Connected to:", url);
});
Here are some relevant docs on the subject, noting that you'll probably want session affinity turned on if you plan on using socket.io in heroku:
https://devcenter.heroku.com/articles/dynos#local-environment-variables
https://devcenter.heroku.com/articles/session-affinity

Unable to connect to socket IO locally in reactjs?

I am using nodeJs as backend and reactJs as my frontend the thing is I emitted a socket emit function from node
var server = require('http').createServer();
var io = require('socket.io')(server);
io.emit('quantity_check', 'KR')
now the issue is I'm unable to catch the emit
let serverUrl = 'localhost:3008'
const socket = socketIOClient(serverUrl);
socket.on("quantity_check", data => this.setState({ kiiii: data }));`
const socket = socketIOClient(serverUrl);
I'm checking this locally even i tried with my ip its not connecting I am not sure where the issue occurs
pc:nodejs and reactjs running on different ports
Can you post the code of you node server file and the react file where are you are listening to the sockets?. Anyway i hope that emit event is inside the connection
io.on('connection', function(socket) {
io.emit('quantity_check', 'KR')
}
and did you use the life cycle method componentDidMount to receive message
componentDidMount() {
socket.on("quantity_check", data => {
console.log(data);
});
}
Try something like this.
server
const server = require('http').createServer();
const io = require('socket.io')(server);
io.on('connect', (socket) => {
io.emit('quantity_check', 'KR');
});
Client(React side)
import io from 'socket.io-client';
const socket = io('http://localhost:3008');
export class App extends Component {
componentDidMount() {
socket.on('connect', () => {
console.log(socket.connected);
});
socket.on("quantity_checke", data => {
console.log(data);
});
}
render().......
}

Why is my connection of a NodeJS server (Sails) to another NodeJS Server (Express4) using Socket.IO failing?

I am trying to connect my Node.JS (written using Sails.JS) app to another Node.JS server (Express4 / Socket.io) using socket.io-client.
My Sails Service app/services/Watcher.js looks like
var client = require('../../node_modules/sails/node_modules/socket.io/node_modules/socket.io-client');
// callback of the form function(socket)
exports.connect = function(callback) {
sails.log.debug("will connect socket to", sails.config.watcher.uri, "with Socket.io-client version", client.version);
var socket = client.connect(sails.config.watcher.uri);
socket.on('connect', function(){
sails.log.debug("connected");
socket.on('disconnect', function(){
sails.log.debug("Disconnected");
});
socket.on('error', function(err){
sails.log.debug("Could not connect", err);
});
callback(socket);
});
};
This is invoked from config/bootstrap.js as follows:
Watcher.connect(function(socket){
sails.log.debug("Connected watcher to relay with socket", socket);
});
On the Express side my server relay.js is as simple as:
var app = require('express')(),
http = require('http').Server(app),
io = require('socket.io').listen(http),
port = process.env.RELAY_PORT || 8000;
app.get('/', function(req, res) {
var response = {message: "some response"}; // to be implemented.
res.json(response);
});
http.listen(port, function () {
console.log("Relay listening on port " + port);
});
io.sockets.on('connection', function (socket) {
console.log("Connection opened", socket);
socket.on('disconnect', function () {
console.log("Socket disconnected");
});
});
When I run node relay it dutifully reports
Relay listening on port 8000
When I sails lift my other server it dutifully reports
will connect socket to http://localhost:8000 with Socket.io-client version 0.9.16
But I never see an actual connection.
If I point a browser at localhost:8000 I get the {"message":"some response"} JSON response I expect.
Why isn't my relay server accepting a connection from my socker.io-client app?
The issue here is probably that you're trying to re-use the
socket.io-client from inside of Sails. In general, if you're require()-ing dependencies of Sails directly in your project, you're heading in the wrong direction. In this case, socket.io-client caches configurations and connections, so your require isn't getting a fresh copy.
Instead, do
npm install socket.io-client#~0.9.16 --save
in your project and require with
var client = require('socket.io-client');
that'll give you a fresh copy of the socket client to work with, and avoid any conflicts with the Sails core's version.

Resources