Not able to connect socket in react native - react-native

I'm trying to connect socket in react native. I am able to connect same socket in html file.
Server Code :
const express = require("express")
, app = express()
, http = require("http").createServer(app)
, fs = require("fs")
, io = require("socket.io")(http);
app.use(express.static("public"));
http.listen("8080", () => {
console.log("Server Started");
});
function socketIdsInRoom(name) {
var socketIds = io.nsps['/'].adapter.rooms[name];
if (socketIds) {
var collection = [];
for (var key in socketIds) {
collection.push(key);
}
return collection;
} else {
return [];
}
}
io.on('connection', function (socket) {
console.log('connection');
socket.on('disconnect', function () {
console.log('disconnect');
});
});
React Native Code:
import io from 'socket.io-client';
const socket = io.connect('http://127.0.0.1:8080', { transports: ['websocket'] });
//const socket = io("http://127.0.0.1:8080"); /* I've also tried this */
socket.on('connect', function (data) {
console.log('connect');
});
I'm using socket.io-client for socket connections in react native

Problem is related to 127.0.0.1 ip. Android can't connect to 127.0.0.1 ip because it is internal loop back IP.
You should replace 127.0.0.1 with your server Ip ether external or internal IP.

Related

Express JS Websocket Connection to wss failed without error but still able to communicate

I am using an Express JS to initiate websocket connection. Below is the following configuration that I used.
socket.js
const ip_address = `${process.env.MIX_HTTPS_APP_URL}`;
const socket_port = `${process.env.MIX_EXPRESS_PORT}`;
const URL = ip_address + ":" + socket_port;
export const socket = io(URL, { autoConnect: true });
socket.onAny((event, ...args) => {
// console.log(event, args);
});
index.js
const app = express();
// app settings
/** Create HTTP server. */
const privateKey = fs.readFileSync(env.privateKey, "utf8");
const certificate = fs.readFileSync(env.certificate, "utf8");
const options = {
key: privateKey,
cert: certificate,
};
const server = https.createServer(options, app).listen(port);
/** Create socket connection */
const socketio = new Server(server);
global.io = socketio.listen(server, {
cors: {
origin: env.url,
},
});
global.io.on("connection", WebSockets.connection);
/** Listen on provided port, on all network interfaces. */
/** Event listener for HTTP server "listening" event. */
server.on("listening", () => {
console.log(`Listening on port:: ${env.url}:${port}/`);
});
Though I can emit and listen to socket, I am still getting this error message. How should I solve this so that users wont see this error message when they view the console?
With reference to your example, the listening on port should be on http server, & socket.io should just attach to on new conn.
see doc https://socket.io/docs/v4/server-initialization/#with-an-https-server
Hope this helps.

Socket.io client is not connecting to the server

I am trying to connect to the socket.io client using the following server-side code...
const express = require("express");
const { createServer } = require("HTTP");
const { Server } = require("socket.io");
const app = express();
const httpServer = createServer(app);
const io = new Server(httpServer);
io.on("connection", (socket) => {
console.log("New user connected");
socket.on("join_room", (room) => {
socket.join(room);
socket.on("message", (msg) => {
io.to(room).emit("update_msg", msg);
});
});
});
const PORT = process.env.PORT || 5000;
httpServer.listen(PORT, () => {
console.log(`Server has started on port number ${PORT}`);
});
My client-side code is as follows.
const socket = io("http://localhost:5000");
socket.emit("join_room", "Room1");
When I am running the above codes it does not print anything in the console. I am using socket.io and socket.io-client version 4.5.0 on the server-side and client-side respectively.
const express = require("express");
const { createServer } = require("http");
const { Server } = require("socket.io");
const cors = require('cors')
const app = express();
app.use(cors())
const httpServer = createServer(app);
const io = new Server(httpServer, { cors: {
origin: "http://localhost:4200",
methods: ["GET", "POST"]
}});
io.on("connection", (socket) => {
console.log("New user connected");
socket.on("join_room", (room) => {
socket.join(room);
socket.on("message", (msg) => {
io.to(room).emit("update_msg", msg);
});
});
});
const PORT = process.env.PORT || 5001;
httpServer.listen(PORT, () => {
console.log(`Server has started on port number ${PORT}`);
});
Hope above code will work.
Please confirm, Did you enable the CORS?, if you're trying to access from different origin.
For your'e reference, I have added the CORS while creating the HTTP Server
Ref: https://socket.io/docs/v3/handling-cors/

React native zoomclone app, how to connect different devices via reactapp and able to render other devices streams

how to connect other devices via socketio and webrtc in a react native app. I have tried using API_URL = my pc's ip address || 5000, can anyone tell me how to connect other android devices after installing the react native app. I am done with the coding part, but in node server I am not able to see any user connected, or mediadetails, or roomID or deviceID? I am using nodejs as backend.
I have tried creating peerServer =new Peer(undefined,{host:"/",port:443}) object inside async function.
I am not able to get massage connected client on the server side. i.e
socket.on('connection', () => console.log('connected client')); this line of code is not able to execute correctly.
server.js code
const express = require('express');
const http = require('http');
const socketio = require('socket.io');
const morgan = require('morgan');
const {ExpressPeerServer} = require('peer');
const { join } = require('path');
const app = express();
const server = http.createServer(app)
const io = socketio(server).sockets;
// Borderparser
app.use(express.json());
const customGenerationFunction = () =>
(Math.random().toString(36) + "00000000000000000").substr(2,16);
const peerServer = ExpressPeerServer(server, {
debug: true,
path:'/',
generateClientId: customGenerationFunction,
});
app.use("/mypeer", peerServer);
io.on('connection', function (socket){
socket.on('join-room', ({roomID, userId}) => {
socket.join(roomID);
socket.to(roomID).broadcast.emit("user-connected", userId);
});
});
const port = process.env.PORT || 5000;
server.listen(port, () => console.log(`Server is running on port
${port}`))
--------------------video-action.js codes-------------------------------
import IO from 'socket.io-client';
import Peer from 'react-native-peerjs';
import AsyncStorage from '#react-native-async-storage/async-storage';
import {mediaDevices} from 'react-native-webrtc';
import {ADD_STREAM, MY_STREAM, ADD_REMOTE_STREAM} from './types';
//* api uri*/
export const API_URI = `http://192.168.01.36:5000`;
//**socket config */
export const socket = IO(`${API_URI}`,{
forceNew: true
})
peerServer =new Peer(undefined,
{
host:'192.168.216.202',
secure: false,
port:5000,
path: '/mypeer',
})
peerServer.on('error', console.log);
socket.on('connection', () => console.log('connected client'));
export const joinRoom = (stream) => async (dispatch) => {
const roomID = 'ahdbflarlkhnlfkjvaerbjhfbjds';
//set my own stream
dispatch({type: MY_STREAM, payload: stream});
//open a connection to our server
peerServer.on('open', (userId) => {
socket.emit('join-room', {userId, roomID});
});
socket.on('user-connected', (userId) => {
connectToNewUser(userId, stream, dispatch)
});
// recieve a call
peerServer.on('call', (call) => {
call.answer(stream);
// stream back the call
call.on('stream', (stream) => {
dispatch({type: ADD_STREAM, payload: stream});
});
});
};
function connectToNewUser(userId, stream, dispatch) {
const call = peerServer.call(userId, stream);
}

Using Secure Websocket on 3 different ports in Nest.js

I have a Nest-Service with the following main.ts:
async function bootstrap() {
if (!!environment.production) {
const app = await NestFactory.create(AppModule, {
httpsOptions: {
key: fs.readFileSync(environment.ssl.SSL_KEY_PATH),
cert: fs.readFileSync(environment.ssl.SSL_CERT_PATH)
},
});
app.useWebSocketAdapter(new WsAdapter(app));
app.enableCors();
await app.listen(3077);
} else {
const app = await NestFactory.create(AppModule);
app.useWebSocketAdapter(new WsAdapter(app));
app.enableCors();
await app.listen(3077);
}
}
bootstrap();
And two Gateways within the Service:
#WebSocketGateway(3078)
export class ItemsGateway implements OnGatewayConnection, OnGatewayDisconnect { ... }
#WebSocketGateway(3079)
export class UnitsGateway implements OnGatewayConnection, OnGatewayDisconnect { ... }
Without SSL this is working, but when I use the prod mode I canĀ“t establish a secure connection to domain.tld:3078 and :3079.
How can I get the service to listen on all 3 Ports? I think there is the problem, because certs are only attached to the Server listening on Port: 3077, where all my REST-API stuff goes.
Thx, Dom
Edit: This also worked as there was just on WebsocketServer on the same port as the API -> 3077.
Edit 2:
I also tried this, but then comes the error that address is in use on the second attempt to create() a server:
async function bootstrap() {
if (!!environment.production) {
const httpsOptions = {
key: fs.readFileSync(environment.ssl.SSL_KEY_PATH),
cert: fs.readFileSync(environment.ssl.SSL_CERT_PATH)
};
const server = express();
const app = await NestFactory.create(
AppModule,
new ExpressAdapter(server)
);
app.useWebSocketAdapter(new WsAdapter(app));
app.enableCors();
await app.init();
https.createServer(httpsOptions, server).listen(environment.app.port);
https.createServer(httpsOptions, server).listen(environment.websocketPorts.units);
https.createServer(httpsOptions, server).listen(environment.websocketPorts.items);
} else {
const app = await NestFactory.create(AppModule);
app.useWebSocketAdapter(new WsAdapter(app));
app.enableCors();
await app.listen(environment.app.port);
}
}
bootstrap();
You need to .create() a separate app for each port on which you listen for wss connections.

Open socket on dynamic endpoint

I am using loopback to build a route:
/users/{id}
where users can listen for new information pertaining to their account on their own endpoint.
I know I need the socket.io package but I'm not sure what to do with it. How can I open a socket on this dynamic endpoint in the function:
#get('/users/{id}', {
responses: {
'200': {
description: 'User socket',
content: {'application/json': {schema: {'x-ts-type': User}}},
},
},
})
async updateUser(#param.path.string('id') userId: typeof User.prototype.id)
: Promise<boolean> {
\\ Open socket here
console.log(userId)
return true;
}
if I do this:
const express = require("express");
const app = express();
const server = require("http").createServer(app);
const io = require("socket.io").listen(server);
const port = 3000;
io.on("connection", socket => {
console.log("User has connected!");
});
It doesn't open a socket on the dynamic endpoint that I want it to.
I am using loopback-4 for the backend and react-native for the front-end.