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.
Related
I have a simple React JS app connected to a socket io server. Whenever I open the app in the browser, the client sends new connection request to the server every 5 seconds.
server:
const express = require('express');
const app = express();
const http = require('http');
const server = http.createServer(app);
const io = require('socket.io')(server);
io.on('connection', (socket) => {
console.log('socket id:', socket.id);
})
server.listen(3001, () => {
console.log('Listening on port 3001');
})
client:
import React from 'react';
import io from 'socket.io-client';
const socket = io('http://localhost:3001');
const App = () => {
return (
<div>Hi there!</div>
);
}
export default App;
logs on the server:
socket id: ByXQEMgeVaQ5AGw1AAAA
socket id: 8LzNQsyeYq7GSEvqAAAB
socket id: bbuYEs4kKzjxXuBsAAAC
socket id: vwprv4hnJbRlStG4AAAD
I suspect there could be something wrong on my laptop, cause I don't see anything wrong in the code, any ideas?
Thanks in advance
I would recommend calling connect inside a useEffect and return the disconnect method to be called when the component dismounts.
const [socket, setSocket] = useState(null)
useEffect(() => {
const newSocket = io('http://localhost:3001')
setSocket(newSocket)
return socket.disconnect()
}, [])
Can you try to wrap the client side socket creation in a useEffect that only runs once? I'm curious to see if the behavior still appears.
import React from 'react';
import io from 'socket.io-client';
const socket = io('http://localhost:3001');
const App = () => {
useEffect(() => {
const socket = io('http://localhost:3001');
}, [])
return (
<div>Hi there!</div>
);
}
export default App;
Actually I just found the root cause, I had a mismatch between my client version and my server version. I updated the client version to v4 and now it is working
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
I am trying to create a socket.io communication between an express app using socket.io (localhost:8000) and a vue app using vue-socket.io (localhost:8080). The express app is receiving emissions from the vue app but not vice versa. Here is my express app though I'm pretty sure the problem lies in the vue app:
Backend Express
const port = 8000
const express = require("express")
const socket = require("socket.io")
const app = express()
const server = app.listen(port, () => {
console.log(`App is lisening to port ${port}...`)
} )
const io = socket(server)
io.on("connection", (socket) => {
console.log("connected to " + socket.id) //this is successfully getting logged
socket.on("chat", (msg) => {
console.log(socket.id + ": " + msg) //this is successfully getting logged when I click send
io.sockets.emit("chat", msg)
} )
} )
I'm guessing the problem is somewhere below:
Frontend Vue (using CLI)
main.js:
import Vue from 'vue'
import App from './App.vue'
import VueSocketIO from 'vue-socket.io'
import SocketIO from 'socket.io-client'
Vue.use(new VueSocketIO( {
debug: true,
connection: SocketIO('http://localhost:8000')
} )
)
Vue.config.productionTip = false
new Vue({
render: h => h(App),
}).$mount('#app')
Chat component (Chat.vue)
<template lang="html">
<div>
<input type="text" v-model="input"/>
<button #click="send">Send</button>
</div>
</template>
<script>
export default {
sockets: {
//These dont work, nothing is printed to the console
connect: function () {
console.log('socket connected')
},
chat: function (msg) {
console.log("chat message recieved!: " + msg)
}
},
data(){
return {
input: ""
}
},
methods: {
send(){
this.$socket.emit('chat', this.input) //This works and is recieved by the express app!
}
}
}
</script>
I've been trying to figure this out for a day now with no luck.
Once again my only goal is to be able to receive emissions front the express app. As a side note if there is a better way to use socket.io in vue without using vue-socket.io I would be glad to investigate.
I was able to get this working simply by using vue-socket.io-extended instead of vue-socket.io. That was it, no major changes to the code necessary. I know technically this doesn't solve the issue using vue-socket.io, but until someone figures that out, I will leave this as the answer for future searchers.
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().......
}
I want to manual test my websocket funcstionality.I am using socket.io and just installed a chrome to extension which allows me to connect to my server and send messages to it.
After some research I found out the sceheme that socket.io uses to send messages - 42["{event}", {data}]
I must be doing something wrong because when I try to send this message I dont trigger my callback.
Here is my server side code:
import * as express from 'express';
import * as http from 'http';
import * as socketIo from 'socket.io';
import config from './config';
const app = express();
const server = http.createServer(app);
const io = socketIo(server);
// URL: ws://localhost:1337/socket.io/?EIO=3&transport=websocket
io.on('connection', function(client: socketIo.Client){
console.log('Client connected..');
io.on('auth', (data:any) => {
console.log(data);
});
});
//start our server
server.listen(config.port, () => {
console.log(`Server listening on port ${config.port}.`);
});
And here is the message which I am sending to my server.
42["auth","test"]
Here is a screenshot aswell.
I get the message when I connect to the websocket, but I cant trigger my callback for the 'auth' command.
I had the code wrong..
io.on('connection', function(socket:SocketIO.Socket){
console.log('Client connected..');
socket.on('auth', (data:any) => {
console.log(data);
});
});