I am trying to set up communication between my nodeJS server and a vueJS app via socket.io. I have been able to get the socket communication working on my main computer so far. When running my node server and my vue app in dev mode, I can open the vue app in the browser and I see the connection coming through my server.
However, when I open the vueJS app on my iPad (connected to the same wifi) the vue app loads and runs fine but my socket connection never goes through. I am also unable to connect to the socket server by opening the vueJS app on differnet PC (also connected to the same wifi as the PC serving the apps) so the iPad is not the issue here.
Could there be something with my local network that would be blocking the connection?
I have tried setting up the socket connection with plain socket.io client, vue-socketIO, and vue-socketIO-extended but each library had the same issue. Here is my code using vue-socketIO-extended:
main.js
import VueSocketIOExt from 'vue-socket.io-extended';
import { io } from 'socket.io-client';
const socket = io('http://localhost:3000');
Vue.use(VueSocketIOExt, socket);
App.js
sockets: {
connect() {
// Fired when the socket connects.
console.log('connect')
},
disconnect() {
console.log('disconnect')
}
}
server.js
const app = require('express')();
const http = require('http').createServer(app);
const io = require('socket.io')(http, {
cors: {
origins: ['http://localhost:8080']
}
});
app.get('/', (req, res) => {
res.send('<h1>Hey Socket.io</h1>');
});
io.on('connection', (socket) => {
console.log('a user connected');
socket.on('disconnect', () => {
console.log('user disconnected');
});
socket.on('my message', (msg) => {
io.emit('my broadcast', `server: ${msg}`);
});
});
http.listen(3000, () => {
console.log('listening on *:3000');
});
That's because the browser tries to connect to the WS server at http://localhost:3000, localhost resolves to IP 127.0.0.1 which is the loopback address of your device, on your iPad localhost is the iPad and there is nothing running on 127.0.0.1:3000 on the iPad.
You need to use the IP of the device that runs your server, Ex:
const socket = io('http://192.168.0.2:3000');
Related
I am trying to connect my quasar application to a socket.io express server hosted on heroku.
The problem is that every time I try to connect, the browser says the request is pending and on the backend I never receive the message of connection.
This is my backend code
const express = require('express');
const app = express();
const PORT = process.env.PORTA || 3000;
const server = app
.use((req, res) => {})
.listen(PORT, () => console.log(`Server is running on port ${PORT}...`));
const io = require('socket.io')(server, {
cors: {
origin: '*',
credentials: true
}
});
io.on('connection', socket => {
console.log('Connected: ' + socket.id);
});
And this is the connection in a boot file in quasar (vue.js) with socket.io extended
import Vue from 'vue'
import VueSocketIOExt from 'vue-socket.io-extended';
import { io } from 'socket.io-client';
const socket = io(URL_CONNECTION);
Vue.use(VueSocketIOExt, socket);
As you can see on the backend I have a console.log to see the id of the connected client. If I try this locally in my pc it works fine and I get the socket id, but on heroku the client doesn't connect without giving me any error.
I found a way to do this. I just removed the custom port I inserted in the server and I put the default (process.env.PORT) and then I connected from the client giving the port 80.
Now, I don't know why, but it's working.
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.
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);
});
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
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.