I try to setup a very basic socket.io bridge between my server (listening on port 8080) and my client (served by react-scripts on port 3000). Nothing happens and I don't even have any error to start debugging.
This is my server :
const server = require('http').createServer()
const Io = require('socket.io')
const io = new Io(server, {
path: '/live'
})
io.on('connection', () => console.log('DID CONNECT'))
server.listen(8080)
And this is my client :
import React from 'react'
import makeSocket from 'socket.io-client'
const socket = makeSocket('http://localhost:8080/live')
socket.on('connect', () => console.log('DID CONNECT'))
export default () => <h1>Demo</h1>
No error, no success log, nothing. What is going on ? Thanks.
Edit : If that may help, it actually seems like I get this error sometimes on browser-side (using Chromium) :
GET http://localhost:8080/socket.io/?EIO=3&transport=polling&t=MuLOZwa net::ERR_EMPTY_RESPONSE
Related
I have built a backend and wanted to test it with some front-end code but for whatever reason, it is just not firing the events on the server. I dont get the "on connect" event triggered. I already downgrade the backend to a version similar to my testing script but still all the server shows, are logs like this.
[22/Oct/2021:14:06:21 +0000] "GET /socket.io/?EIO=4&transport=polling&t=NoeKlFT&b64=1 HTTP/1.1" 404 149 "-" "node-XMLHttpRequest"
I am using socket io for server and client version 3.1.2
Here is the backend code snippet
const dotenv = require("dotenv").config();
const express = require("express");
const app = express();
const server = require("http").createServer(app);
const io = require("socket.io")(server);
const morgan = require("morgan");
const cors = require("cors");
const config = require("./src/config/general");
const exchangeController = new ExchangeController(io); // I want to pass in the IO obejct to be able to deal with all the event stuff in another file besides the apps entry point file.
Here is the part where I want the IO object to be available and work with the events from there
class ExchangeController {
constructor(io) {
this.io = io;
this.exchangeService = new ExchangeService();
this.router = express.Router();
this.initRoutes();
this.io.on("connection", (socket) => {
console.log("incoming socket connection"); //gets never logged to console when connecting frontend
//do further stuff (deleted for post)
});
});
}
This is the frontend script for testing the connection
//client.js
const io = require('socket.io-client');
const socket = io("mysecreturl") //also tried localhost instead of deployed app url no difference
// Add a connect listener
socket.on('connect', function (socket) {
console.log('Connected!');
});
I really tried for way too long now without getting any results. I hope you guys can guide me on the right path again.
Cheers
I am new to node JS and I am trying to create a real time application that consists of a node JS server with socket.io and a unity application that can connect to it
I created the server with the sockets in the below code :
const express = require('express');
const http = require('http');
const app = express();
const port = process.env.PORT || 9000;
const server = http.Server(app);
const io = require('socket.io')(server);
io.on('connection',(socket) => {
console.log('A user connected');
socket.on('disconnect', () => {
console.log('user disconnected');
});
})
app.get('/',(req,res) =>{
res.json({worked : 'worked'});
});
server.listen(port,() => console.log(`Listening on localhost ${port}`));
I can connect to the socket server via the nodejs client files using socket.io-client
<script>
const socket = io('http://localhost:9000');
socket.on('message',(message) => console.log(message));
</script>
But the problem is whenever I try to connect from a different client I don't receive anything in the console.
I tried to use Smart Web Socket client to debug what's happening but whenever I connect (try to)
this happens
Any help would be much appreciated and thanks in advance
So if anyone stumbles in this thread I was able to fix the problem by installing the latest version of socket.io (^3.1.0) and allowing the EIO3 connections
I'm running an express based apollo graphQL server using apollo-server-express.
import express from 'express'
import cors from 'cors'
import server from './graphql/schema'
app.use(cors())
server.applyMiddleware({ app, path: '/graphql' })
app.listen(port, async () => {
if (process.env.NODE_ENV !== 'production') {
console.log('Listening on port ' + port)
}
})
export default app
Now I need to connect to some other applications from my client. Therefore he provides me with HL7 data. He told me to 'use a socket to get the HL7 data', which my application can use.
I just don't have a clue how to implement a socket connection at all.
Doing some researches brought me to libraries like socket.io, which should be used like this (for express):
const app = require('express')();
const server = require('http').createServer(app);
const io = require('socket.io')(server);
io.on('connection', () => { /* … */ });
server.listen(3000)
I don't understand how to implement the io in my existing code shown above.
I never used or implemented a socket connection at all, so I have very big understanding problems with that. Maybe the socket.io library is not the correct thing for my needs.
I do not have any knowlege about HL7 data, I think your another app has been writen by Java.
But, if you want to implement a socket.io server with apollo-server-express, just follow socket.io official document and attach a http server to express app and socket.io, then start your http server.
import express from 'express'
import cors from 'cors'
import GraphQLServer from './graphql/schema'
import socketIO from 'socket.io'
import http from 'http'
let app = express() // You missed this line ?
let httpServer = http.Server()
let io = socketIO(httpServer)
app.use(cors())
GraphQLServer.applyMiddleware({ app, path: '/graphql' })
httpServer.listen(port, async () => { // I don't see your `port`
if (process.env.NODE_ENV !== 'production') {
console.log('Listening on port ' + port)
}
})
io.on('connection', (socket) => {
console.log('A client connected', socket.id)
});
export default app
I have built a React app that is connected to a local running express node server with socket.io. Everything works fine but after a few hours of 100+ sending requests, and listening to those changes from the local server to the client it starts to slow down and won't work as efficiently until I reload the client window sessions.
I have a very difficult time troubleshooting this. Do you think it has something to do with my node server setup, or is it something with my client? Or maybe it's hardware issues? One thing I notice is that how my client keeps connecting to socket.io from the console.
const express = require('express')
const http = require('http')
const socketIO = require('socket.io')
// localhost port
const port = 4001
const app = express()
// server instance
const server = http.createServer(app)
// creates socket
const io = socketIO(server)
io.on('connection', socket => {
socket.on('change view', (view) => {
console.log('view changed to: ', view)
io.sockets.emit('change view', view)
})
})
server.listen(port, () => console.log(`Listening on port ${port}`));
React app client side:
componentDidMount() {
const socket = socketIOClient(this.state.endpoint);
socket.on('change view', (col) => {
callAfunctionThatDoesSomething(col);
})
};
When I send changes to the server
send = () => {
const socket = socketIOClient(this.state.endpoint);
socket.emit('change view', this.state.view);
}
Any ideas?
You are connecting to socket.io two times. First at componentDidMount and second, when calling send(). Which is not recommended.
You should connect to socket one time. You can connect in componentDidMount method of a component. But if you want to use socket in multiple component. This will also connect to socket multiple time.
I will say you connect to socket one time when registering routes or your whole app. I created a sample app before. You can check it.
https://github.com/vkasraj/random.ly
I am working on a node project where I need to use websockets. I got the basic implementation working for socket.io in my project. Here is the code for server.js so far
import app from '../app';
import http from 'http';
import socket from 'socket.io';
var server = http.createServer(app);
server.listen(app.get("port"));
server.on('error', onError);
server.on('listening', onListening);
const io = socket(server);
io.on('connection', (socket) => {
console.log(`connected ${socket.id}`);
socket.on('disconnect', () => {
console.log('disconnected');
});
});
Now if I need to call socket from another javascript file, how do I do that?
Something like this: From a.js I would like to call emit message from download function. The problem is that I don't have reference to socket object in a.js. It was defined in my server.js file. Any suggestions?
export const download = () => {
//after file is downloaded, emit message using socket.io to user
}
you need to inject the object into a function that you're calling. is a Dependency Injection principle in programming.
you can
a.js
export const download = (io) => { // io is the reference
//do something with io like io.emit
}
then in your server you need to import the download function then pass the io in your code.
import {download} from "<src/file/of/a.ts>"
// somewhere in the code in server.js
download(io);
for Dependency Injection Principle reference https://en.wikipedia.org/wiki/Dependency_injection
and What is dependency injection?