This is the code on client,
const url = "localhost:8080"
const socket = socketIOClient(url);
socket.on("broadcast", (value) => {
this.props.getUpdate(value)
})
This is the code on Server nodejs express,
io.on('connection', function(socket){
console.log('A user connected');
});
the console.log on the server is running more than once intervally i dont know why?
note: client is react with redux
edit:
componentDidMount() {
const url = "localhost:8080"
const socket = socketIOClient(url);
socket.on("broadcast", (value) => {
this.props.getUpdate(value)
})
}
I just create socket in componentDidMount function.
https://github.com/Mrbiyik/platraFrontend
this is the repo of this code
edit:
It is creating this request intervally
Related
I just set up SocketIO in my PHP project. I am completly new to websockets at all so bear with me.
I am defining the socketIO variable globally
let socketIO = io("http://localhost:3000");
When people are logging in to my application, they are connected to it with their ID comming from the database. The login script just gives back true which redirects the user in very simplified terms:
// get component
$.get(url, data, (data) => {
if (data.status) {
// connect with Node JS server
socketIO.emit("connected", data.user_id);
// redirect
load_new_page("/users/" + data.user_id);
}
});
My concern here now is that people could just go and change the data.user_id to anything they want and receive what ever the chosen id would receive.
My server.js:
// initialize express server
var express = require("express");
var app = express();
// create http server from express instance
var http = require("http").createServer(app);
// include socket IO
var socketIO = require("socket.io")(http, {
cors: {
origin: ["http://localhost"],
},
});
// start the HTTP server at port 3000
http.listen(process.env.PORT || 3000, function () {
console.log("Server started running...");
// an array to save all connected users IDs
var users = [];
// called when the io() is called from client
socketIO.on("connection", function (socket) {
// called manually from client to connect the user with server
socket.on("connected", function (id) {
users[id] = socket.id;
});
});
});
How can I prevent something like this?
I have an issue trying to connect a reactJS app with a nodeJS API using socket.io.
Here's API code :
const httpServer = require('http').createServer();
const io = require('socket.io')(httpServer);
httpServer.listen(8080, () => {
console.log('go to http://localhost:8080');
});
io.on('connection', socket => {
console.log('client connected');
});
And reactapp :
import React from "react";
import socketIOClient from "socket.io-client";
const ENDPOINT = "http://localhost:8080";
function App(){
const socket=socketIOClient.connect(ENDPOINT);
return(<p>Hello</p>);
}
export default App;
As you can see, it is a simple code but still it doesn't work.
The 'client connected' message from the API never shows up.
It looks like the react app can't connect to the port even if it's open or idk.
It may happen because of syntax in the react app side. Can you try this one in the function?
function App(){
let socket = io(ENDPOINT, {
transports: ["websocket"],
});
console.log("Connecting...");
socket.on("connect", () => console.log("Connected!"));
}
or you can define socket outside of the function.
I hope to get some answers here as i have been trying to debug for few days now.
The expected behaviour:
socket in server connected once when user is in my website.
The actual behaviour:
socket in server connected twice when user is in my website.
I am using Next.js as the front end and node server as backend.
_app.js
const MyApp = () => {
useEffect(() => {
socket.once('connect', () => {
console.log('Connected');
});
return () => {
socket.disconnect();
};
}, []);}
server.js
let connections = [];
module.exports = function (io) {
io.on('connection', async (socket) => {
console.log(socket.id + ' connected', '\n');})}
after hours of research, i finally found the answer!
How To Implement React hook Socketio in Next.js
I followed the top answer and it worked! because nextjs render once in its server and its client.
I am using socket.io in a react - node project. I have a problem with the socket not refreshing when the page refreshes.
It works first as the server and the react dev server run for the first time. After using the socket ( emitting something from the server ), refreshing the browser page would result in an error in the web socket.js file :
WebSocket connection to
'ws://localhost:4000/socket.io/?EIO=3&transport=websocket&sid=XTE63CeWdp676cRXAAAF'
failed: Error during WebSocket handshake: Unexpected response code:
400
here is the code I use in client and server :
SERVER :
const express = require('express');
const socketconfig = require('./socket.io');
class Server {
constructor({ config, router, logger, }) {
this.config = config;
this.logger = logger;
this.express = express();
this.express.disable('x-powered-by');
this.express.use(router);
}
start() {
return new Promise((resolve) => {
const http = this.express
.listen(this.config.web.port, () => {
const { port } = http.address();
this.logger.info(`[p ${process.pid}] Listening at port ${port}`);
resolve();
});
var io = require('socket.io').listen(http,function () {
console.log("I AM CONNECTIONG")
});
this.freshio=io.sockets;
socketconfig.setOnConnection(this.freshio, ()=>{
console.log('Connexion COnditions are set');
});
socketconfig.setOnDisconnect(this.freshio, ()=>{
console.log('client disconnected');
});
this.clients = socketconfig.clients;
});
}
}
module.exports = Server;
the start() method would be called when the server is initiated.
the socketConfig file is just a toolkit for saving clients and setting conditions, it doesn't interfere with anything.
CLIENT :
import openSocket from 'socket.io-client';
let url = Store.config.socketserverurl + ":" + Store.config.socketserverport;
const socket = openSocket.connect(url);
Store is just the flux store that has the config files linked to it.
I have tried adding the webSockets method of using socket.io instead of the http method but that was in vain as an other problem spiraled.
what should I do ?
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().......
}