Socket.io can't find the server - javascript

I am trying to use socket.io in my server. But it gives me this error: GET http://localhost:4000/socket.io/socket.io.js net::ERR_ABORTED 404 (Not Found)
Here is my server code:
const app = express();
const http = require('http');
const server = http.createServer(app);
var io = require('socket.io')(server);
const taskRouter = require("./routers/tasks.js")
app.use( "/" , taskRouter)
io.on('connection', function (socket)
{
console.log("Connected!")
})
app.listen(PORT, () => {
console.log(`Server is on port ${PORT}`);
});
Here is my pug code:
extends ../header2.pug
block unique-css
include ../../public/css/mentor/chat.css
block unique-content
.main
h1 Hello World!
script(src="/socket.io/socket.io.js")
script
include ../../public/js/mentor/chat.js
Here is my client-side javascript code:
var socket = io()
socket.on('connection', function (data) {
console.log("helloworld");
});
And the problem is when I try to use socket.io I get this errors in browser GET http://localhost:4000/socket.io/socket.io.js net::ERR_ABORTED 404 (Not Found), Uncaught ReferenceError: io is not defined. The second error is pointing to the first line of frontend js code.

Use server.listen(port)
const app = express();
const http = require('http');
const server = http.createServer(app);
var io = require('socket.io')(server);
const taskRouter = require("./routers/tasks.js")
app.use( "/" , taskRouter)
io.on('connection', function (socket)
{
console.log("Connected!")
})
//changes below
server.listen(PORT, () => {
console.log(`Server is on port ${PORT}`);
});
And in the client-side you don't require this code. Delete this.
socket.on('connection', function (data) {
console.log("helloworld");
});

Related

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());

Simple server-client socket io

I'm trying to set up a simple server/client architecture using socket.io.
I have the following code in my main.js
var app = require('express')();
var http = require('http').createServer(app);
var io = require('socket.io')(http);
app.get('/', (req, res) => {
res.send('<h1>Hello world</h1>');
});
io.on('connection', function(socket){
console.log('a user connected')
})
http.listen(3001, () => {
console.log('listening on *:3001');
});
I have the following code in my client.js
const io = require("socket.io-client");
let socket = io(':3001')
I then run node main.js which prints "listening on *:3001", however when I run node client.js the expected "a user connected" is not printed. What am I missing in this simple architecture?
It should work if you write it like this in your client.js:
let socket = io('http://localhost:3001/')

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/

Socket io not working after being deployed

I'm not getting an error but io.on('connection', function(socket){
console.log('a user connected', socket.client.id);
}); doesn't seem to work when I deployed my application in Linode.
But in the development it's working fine.
server.js ( socket io )
var express = require('express');
var app = express();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var port = 8002;
io.on('connection', function (socket) {
console.log('a user connected', socket.client.id); // triggering in the development
});
http.listen(port, function () {
console.log('Express server listening on port ' + port);
console.log('env = ' + app.get('env') +
'\n__dirname = ' + __dirname +
'\nprocess.cwd = ' + process.cwd());
});
client html ( note: i change the localhost to my web app ip)
<script src="http://localhost:8002/socket.io/socket.io.js"></script>
and my application seem to be using the socket.io polling-xhr.js
I'm kind of new to this.
I don't know if this will fix your particular problem, but in order to set up socket.io on the same port that your application uses you can configure it this way:
const express = require('express');
const app = express();
const http = require('http');
const hostname = 'localhost';
const port = 80;
// the express app is registered with the server
const server = http.createServer(app);
// setup socket.io and register it with the server
const io = require('socket.io').listen(server);
// tell the application to listen on the port specified
server.listen(port, hostname, function (err) {
if (err) {
throw err;
}
console.log('server listening on: ', hostname, ':', port);
});
Now socket.io runs on the same port as your application.

Categories

Resources