I'm having trouble with connect to my socket.io server, I want user to be connected when on.connection, here's my server code
const express = require('express');
const http = require('http');
const socketio = require('socket.io');
const cors = require('cors');
const {getUserList, get_Current_User, user_Disconnect, join_User, playByTurn } = require("./dummyuser");
//Set static folder
const app = express();
app.use(cors());
const server = http.createServer(app);
const io = socketio(server, {
cors: {
origin: "http://localhost:8080",
methods: ["GET","POST"]
}
});
const PORT = process.env.PORT || 8000;
//Run when client connect
//Run when client connect
io.on('connection', socket => {
console.log(`Connected: ${socket.id}`);
//Code
});
socket.on('disconnect', () => {
console.log(`Disconnected: ${socket.id}`);
//Code
})
});
server.listen(PORT, () => console.log(`Server running on port ${PORT}`));
On my localhost it works just fine, but after I deploy it said that it can't GET from my server, any ideas? Thanks
I was finally solved it by adding transports: ['websocket'] in my client code
import io from 'socket.io-client';
const socket = io("//url",{
transports: ['websocket'],
});
Related
i wrote simple web socket code by socket.io and the code run with no error and i can access it via browser with address localhost:5000. but when i test the connection with Socket.IO Test Client chrome extension or any other websocket tester it return error "connection error: xhr poll"
my code
const objExpress = require('express');
const objApp = objExpress();
const objHTTP = require('http');
const objServer = objHTTP.createServer(objApp);
const {Server} = require('socket.io');
const objIO = new Server(objServer);
objServer.listen(5000,"localhost", () => {
console.log("listening to port 5000");
});
do i miss something?
I made a socket.io server and this is how it worked for me:
const express = require('express');
const app = express();
const server = require('http').Server(app);
const io = require('socket.io')(server, {
cors: {
origin: "*",
methods: ["GET", "POST"],
},
});
const PORT = process.env.PORT || 3000
server.listen(PORT, () => console.log(`Server running on port ${PORT}`));
Not working can't find any issue in code##
If I put any port number instead of server it's working but why didn't it's working with socket server anyone explain
I tried some solution but none of them work I want to run socket.io and express on same port number
const express = require('express');
const cors = require("cors");
const socketIO = require('socket.io');
const http = require('http');
const app = express();
const server = http.createServer(app);
const passport = require("passport");
const authRoute = require('./routes/auth');
const userRoute = require('./routes/user');
const PORT = process.env.PORT || 9000;
const db = require('./config/mongoose');
app.use(express.json());
app.use(cors());
app.use(passport.initialize());
require("./config/passport")(passport);
app.use(express.json());
app.use("/api/auth", authRoute);
app.use("/api/user", passport.authenticate('jwt', { session: false }),userRoute);
if(process.env.NODE_ENV === 'production')
{
app.use(express.static('client/build'))
}
Here is the issue if I switch server to any port number it's fine
const io = socketIO(server, {
cors: {
origin: '*',
}
});
let state = {};
io.on("connection", (socket) => {
const { id } = socket.client;
socket.on('disconnect', function () {
console.log('socket disconnected!');
});
socket.on('join_room', function (data) {
console.log('joining request rec.', data);
socket.join(data.room);
io.in(data.room).emit('user_joined', data);
});
socket.on('send_code', function (data) {
io.in(data.room).emit('receive_code', data);
});
});
app.listen(PORT, function (err) {
if(err){
console.log(err);
return;
}
console.log(`Server is up and running on port: ${PORT}`);
});
http.createServer(app) and app.listen() are not compatible as they both try to do the same thing. If you look at the source code for app.listen(), you will see this:
app.listen = function listen() {
var server = http.createServer(this);
return server.listen.apply(server, arguments);
};
So, it's creating a DIFFERENT server object. You end up with two and the first one never gets started so when you give it to socket.io, it never works.
Instead, remove this:
const server = http.createServer(app);
And, use this instead:
const server = app.listen(PORT, function (err) { ...});
This way, your server variable will contain the one and only server object that is actually running.
Alternatively, you could remove the app.listen() and then just add this in it's place:
server.listen(PORT, ...);
The general idea is that you want this pair:
const server = http.createServer(app);
server.listen(PORT, ...);
Or, just this:
const server = app.listen(PORT, ...);
You cannot use both. Either way, that server object will represent the server that is actually running and will work with socket.io.
I have an Express server which works well, but now I want to set up Socket.io in it,
I have the error TypeError: require(...).listen is not a function
My current code (working well)
const app = express();
app.set("port", process.env.PORT || 5000);
app.listen(app.get("port"), () => {
console.log("Server running");
});
Code trying to set up Socket.io
const port = process.env.PORT || 5000;
const server = app.listen(port, () => {
console.log("Server running");
});
const io = require("socket.io").listen(server);
Can someone help me with the error above please ?
From the SocketIO documentation, to setup SocketIO with the express application, it should be:
const express = require('express');
const app = express();
const http = require('http');
const server = http.createServer(app);
const { Server } = require("socket.io");
const io = new Server(server);
io.on('connection', (socket) => {
console.log('a user connected');
});
I am trying to develop a simple chat app using Node, React, Express & Socket.io.
Here is my Node server set up:
const express = require("express");
const cors = require('cors');
const http = require('http');
const socketio = require('socket.io');
// ENV VARS
if (process.env.NODE_ENV !== 'production') {
require('dotenv').config();
}
const SERVER_PORT = process.env.SERVER_PORT || 5000;
const HOST = process.env.HOST || "http://localhost";
// INIT
const app = express();
const server = http.createServer(app);
const io = socketio(server);
// MIDDLEWARE
app.use(cors());
app.use(express.urlencoded({extended: false}));
app.use(express.json());
io.on('connection', (socket) => {
console.log('new client connected');
});
// ON LISTEN
server.listen(SERVER_PORT, () => {
console.log(`app listening at ${HOST}:${SERVER_PORT}`);
});
Here is my client side:
import {io} from "socket.io-client";
import './App.css';
const PORT = 5000
const HOST = "http://localhost"
const SERVER_URL = HOST + ':' + PORT
console.log(SERVER_URL);
function App() {
let socket = io(SERVER_URL);
return (
<div className="App">
aaaa
</div>
);
}
export default App;
I simply tried to test the on connection event, Yet I am getting the following error:
Access to XMLHttpRequest at 'http://localhost:5000/socket.io/?EIO=4&transport=polling&t=NbN5Yrt' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
polling-xhr.js:203 GET http://localhost:5000/socket.io/?EIO=4&transport=polling&t=NbN5Yrt net::ERR_FAILED
i tried adding:
{origins: '*'}
as socket io doc says but the errors are still showing.
What am I doing wrong?
I think changing the order of initialization could help, because your server lacks all the middleware applied to app.
// INIT
const app = express();
// MIDDLEWARE
app.use(cors());
app.use(express.urlencoded({extended: false}));
app.use(express.json());
// Create server and listen on PORT after adding middleware
const server = app.listen(PORT, () => {
console.log(`app listening at ${HOST}:${SERVER_PORT}`)
});
// Try to avoid wilcard ('*') origins
const io = socketio(server, { cors: { origin: '*' } });
// Handle socketio connections
io.on('connection', (socket) => {
console.log('new client connected');
});
// EOF
I don't know what else to try
My server:
const express = require("express");
const http = require("http");
const app = express();
const server = http.createServer(app)
const cors = require('cors');
app.use(cors());
app.options('*', cors());
const socketio = require('socket.io')
const io = socketio(server);
io.on("connect", socket => {
console.log("hello");
socket.on("welcome ", (e) => {
console.log(e)
})
});
const port = 8081;
server.listen(port, () => console.log(`listen on port ${port}`))
in app react
import io from "socket.io-client";
let socket = io.connect("http://localhost:8081");
socket.emit("welcome", "connected");
react run port 3000
nodejs run port 8081
but everything I try throws error.