How can I get Socket.io to connect again? - javascript

In my Node.js backend I have the following code which is supposed to set up the Socket.io connection:
const express = require("express");
const app = express();
const { createServer } = require("http");
const httpServer = createServer(app);
const port = 3001;
const io = require("socket.io")(httpServer, { cors: { origin: "*" } });
io.on("connection", (socket) => {
console.log("Connected!");
socket.on("join-room", (id) => {
socket.join(id);
console.log(`user joined room ${id}`);
});
});
Previously this was working, but for some reason it isn't anymore. When I started my server today I wasn't able to get Connected! logged to the console, nor was user joined room logged to the console when that event was triggered. Is there something wrong with how I'm establishing this connection?

Related

Address already in use with Socket.io in Express

I'm trying to use websockets in my app but I'm not able to get Socket.io to connect to my server. Whenever I run the code below, I get this error:
Error: listen EADDRINUSE: address already in use :::3000
I've tried looking up some solutions, and I found that there's no other processes running on this port, so the issue has to be within the project. What could I be doing wrong here?
const express = require("express");
const mongoose = require("mongoose");
const app = express();
const { createServer } = require("http");
const httpServer = createServer(app);
const socketIO = require("socket.io")(3000, { cors: { origin: "*" } });
socketIO.on("connection", (socket) => {
console.log("connected");
});
const port = 3000;
const startServer = () => {
httpServer.listen(port);
console.log(`Listening on port ${port} 🚀`);
};
mongoose
.connect(uri)
.then(() => startServer())
.catch((err) => {
console.log(err);
});
If you don't supply socket.io with an http server, it will create one for you. So your code is actually creating two http servers, both trying to listen on the same port which fails with EADDRINUSE.
Instead, pass the httpServer as the first parameter to socket.io instead of a port number:
const socketIO = require("socket.io")(httpServer, { cors: { origin: "*" } });
It's happening because
const startServer = () => {
httpServer.listen(port);
console.log(`Listening on port ${port} 🚀`);
};
here already the address 3000 in use ... so you shouldn't pass the port:3000 into socketIO, better pass the httpServer, like :
const socketIO = require("socket.io") (httpServer, cors: { origin: "*" } });
socketIO.on("connection", (socket) => {
console.log("connected");
});

WebSocket - can't connect (Expected HTTP/)

I am using Node.JS and I am using http to use an express server which then my WebSocket is on, but when I try to connect to the socket it gives me an 'Expected HTTP/' error.
My code:
const express = require('express');
const app = express();
const server = require('http').createServer(app);
app.get('/', (req, res) => {
res.send("Hello World!");
});
const wss = new WebSocket.Server({ server });
// web socket stuff here
server.listen(port, () => {
console.log(`HTTP Server started on port ${port}`);
});
And then on another Node project, I have this to connect:
const WebSocket = require('ws');
const ws = new WebSocket.WebSocket('ws://localhost:3000/ws');
Any help?
//my memory in this question was that
const WebSocket = require('ws');
const socket = new WebSocket.Server({ port: 2424, host: "localhost"});
socket.on('connection', function(ws, wss) {
var domain = wss.headers.origin;
//etc...
But maybe you have a front for communicate if is not the good response ?

socket io client not connecting to server using ipv4 address

I'm having a problem with testing the connection when I use https://localhost:3000/ it connects successfully but I want to use socket Io client on a different device on android application to be precise I searched it up and turns out localhost wont work I have to connect using ipv4 address well I tried it but didnt work - like this http http://192.168.XX.XX:3000 for example so what is the problem why doesnt it connect please help
server code:
var cors = require("cors");
const express = require("express");
const app = express();
const port = process.env.PORT || 3000 ;
const server = app.listen(port, () => {
console.log(`started on ${port}`);
})
const io = require('socket.io')(server, {
cors: { origin: "*" }
});
io.on('connection', (socket) => {
console.log('a user connected');
socket.on('message', (message) => {
console.log(message);
io.emit('message', `${socket.id.substr(0,2)} said ${message}` );
});
});
require("dotenv").config();
app.use(express.json());
app.use(cors());
//routes setup
const homeGetRoute = require("./routes/test.js");
app.use("/home", homeGetRoute);
app.use(cors());

Should I create a route specific for SocketIO?

I'm a newbie to Socket.IO, I did the chat tutorial of the docs and the "homework" of the chat app to understand how it works, now I'm trying to connect an NodeJS server and a React App with a Socket. I've spent all day trying to do this, but I'm getting this error:
GET http://localhost:4000/?EIO=4&transport=polling&t=NYW26Ea 404 (Not Found)
The itention of my app is show an update of time, I'm using socket to update time on screen each one second.
Here's my Server.js file, and yes, it is pretty simple:
const express = require("express")
const http = require("http")
const socketIO = require("socket.io")
var cors = require('cors')
const PORT = 4000;
const routes = require("./routes/index")
const app = express()
app.use(cors())
app.use(routes)
const server = http.createServer(app)
const io = socketIO(server)
let interval
io.on("connection", (socket) => {
console.log("New client connected!")
if(interval) {
clearInterval(interval)
}
interval = setInterval(() => getApiAndEmit(socket), 1000)
socket.on("disconnect", () => {
console.log("Client is disconnected")
clearInterval(interval)
})
})
const getApiAndEmit = socket => {
const response = new Date()
socket.emit("from-api", response)
}
app.listen(PORT, () => console.log(`Application up and running on ${PORT}`))
If I visit the route I created with express it works fine.
And here is my App.js file:
import React, { useState, useEffect } from "react";
import socketIOClient from "socket.io-client";
const ENDPOINT = "http://127.0.0.1:4000";
function App() {
const [response, setResponse] = useState("");
useEffect(() => {
const socket = socketIOClient(ENDPOINT);
socket.on("from-api", data => {
setResponse(data);
});
}, []);
return (
<p>
It's <time dateTime={response}>{response}</time>
</p>
);
}
export default App;
Should I create a route for SocketIO or what?
Should I create a route for SocketIO or what?
No. When you do this:
const io = socketIO(server)
The socket.io library already installed its own route handler for routes starting with /socket.io and any other routes it needs. You don't need to do that yourself.
You do, however, have a problem because you're hooking up socket.io to server that you never started.
When you do this:
app.listen(PORT, () => console.log(`Application up and running on ${PORT}`))
That creates a new http server and then calls .listen() on it and returns that new server. You will need to capture that server and hook up socket.io to it:
So, replace this:
const server = http.createServer(app)
const io = socketIO(server)
app.listen(PORT, () => console.log(`Application up and running on ${PORT}`))
With this:
const server = app.listen(PORT, () => console.log(`Application up and running on ${PORT}`))
const io = socketIO(server);
Then, you're creating and starting just one http server and hooking up both Express and socket.io to it. They can both share the same http server on the same port. Socket.io will use the route prefix /socket.io to distinguish its own routes and once a given socket.io connection has been established, that specific connection switches protocol to the webSocket protocol (with socket.io data frame on top of it) and is no longer using http any more.
Instead of:
app.listen(PORT, () => console.log(`Application up and running on ${PORT}`))
Use this:
server.listen(PORT, () => console.log(`Application up and running on ${PORT}`))
Reason: The server instance you are assigning to socketIO is not the same as the instance of server you are listening to.
With express you can pass the server instance like this:
var express = require('express');
var app = express();
...
...
...
var server = app.listen(PORT);
var io = require('socket.io').listen(server);
io.sockets.on('connection', function (socket) {
...
});
You can refer this: Express.js - app.listen vs server.listen

Adding socket.io to an existing Express project (with React on the front)

I have an existing project written in Express, where I've made a messaging system. Everything was working on POST/GET methods (to send and receive the messages).
I wanted to make them appear in real time, so I installed socket.io both on the client and server side. In my server.js I added these lines:
const http = require("http");
const io = require("socket.io");
const server = http.createServer();
const socket = io.listen(server);
and changed my app.listen(...) into server.listen(...).
Added also:
socket.on("connection", socket => {
console.log("New client connected");
socket.on('test', (test) => {
console.log('test-test')
});
socket.emit('hello', {hello:'hello!'});
socket.on("disconnect", () => console.log("Client disconnected"));
});
On the front part I put such code in the componentDidMount method:
const socket = socketIOClient();
socket.emit('test', {test:'test!'})
socket.on('hello', () => {
console.log('aaa')
})
Now I got 2 problems. Although the console.log() works correctly, I get an error on the React app:
WebSocket connection to 'ws://localhost:3000/sockjs-node/039/lmrt05dl/websocket' failed: WebSocket is closed before the connection is established.
Is that normal?
Also, when I change app.listen(...) into server.listen(...) in the server.js file, my routing stops working. All the POST and GET methods don't work, because the server is responding endlessly. Is that possible to use the socket.io just on a specific method in a specific routing file?
I keep my routes that way: app.use('/api/user', user); where user is a router file.
UPDATE:
full server.js require:
const express = require('express');
const mongoose = require('mongoose');
const dotenv = require('dotenv');
const bodyparser = require('body-parser');
const passport = require('passport');
const user = require('./routes/api/v1/User');
const company = require('./routes/api/v1/Company');
const http = require("http");
const io = require("socket.io");
const app = express();
dotenv.config();
app.use(passport.initialize());
require('./config/seed');
require('./config/passport')(passport);
const server = http.createServer();
const socket = io.listen(server);
You're not initializing server properly. Try making the following change
// const server = http.createServer();
const server = http.createServer(app);
and make sure you listen on server and not io
server.listen(PORT_GOES_HERE)
[UPDATE]
Working Example:
var app = require('express')();
var server = require('http').Server(app);
var io = require('socket.io')(server);
server.listen(80);
// WARNING: app.listen(80) will NOT work here!
// DO STUFF WITH EXPRESS SERVER
app.get('/', function (req, res) {
res.sendFile(__dirname + '/index.html');
});
io.on('connection', function (socket) {
socket.emit('news', { hello: 'world' });
socket.on('my other event', function (data) {
console.log(data);
});
});
For more details check this: https://socket.io/docs/

Categories

Resources