I been stuck on this for hours. I am able to run the code fine locally but when I try to deploy on heroku it throws a 404 error on my socket.
Server code
'use strict';
const express = require('express');
const socketIO = require('socket.io');
const path = require('path');
const PORT = process.env.PORT || 3000;
const server = express()
.use(express.static('public'))
.listen(PORT, () => console.log(`Listening on ${ PORT }`));
const io = socketIO(server);
io.on('connection', (socket) =>{
console.log("connection to socket", socket.id);
});
Client Code:
var socket = io();
socket.emit('email', {
fullName: fullName.value,
numOfGuest: numOfGuest.value,
guestName: guestName.value,
emailAddress: emailAddress.value,
guestStatus: status
});
Apps using Socket.io should enable session affinity.
heroku features:enable http-session-affinity
More about session affinity on heroku: https://devcenter.heroku.com/articles/session-affinity
Related
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'],
});
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 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.
I am writing this server app (express and socket.io), just at the beginning.
I see double log, so I have double connection to server when starting a tab at localhost:8080.
What am I doing wrong? Is this a Socket.io bug?
const express = require("express");
const path = require("path");
const socket = require("socket.io");
const port = process.env.PORT || 8080;
const app = express();
const server = app.listen(port);
app.use(express.static(__dirname + "/dist"));
app.get("/", (req, res) => {
res.sendFile(path.resolve(__dirname + "/dist", "index.html"));
});
// Socket setup
const io = socket(server);
io.on("connect", function (socket) {
console.log("Made socket connection");
});
The problem was that more js client files were calling socket().
Right method is to import socket.io library in , into your html file, so that this will be available to all js client file, implementing only one connection.
I'm having trouble trying to figure out why I'm getting this 404 error. I've gone through all the other questions on this site that cover 'express-ws' and i've modeled my code exactly how the solutions prescribed yet the websocket won't make a connection. I'm trying to create a websocket connection between my express server and react app. Below are previews of my code:
Express using express-ws (server.js):
var express = require('express');
var expressWs = require('express-ws');
var bodyParser = require('body-parser');
var cors = require('cors');
var nodemailer = require('nodemailer');
var email = require('./credentials');
var port = process.env.PORT || 3001;
var path = require('path');
// const WebSocket = require('ws');
// const http = require('http');
expressWs = expressWs(express());
let app = expressWs.app;
var server = require('http').createServer(app);
app.use(cors());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
if (process.env.NODE_ENV === 'production') {
app.use(express.static('app/build'));
}
app.get('/', function(req, res){
console.log('server running!');
res.end();
});
app.ws('/ws', function(ws, req) {
console.log( 'socket running!' );
});
server.listen(port);
console.log('server started on port ' + port);
The GET route works fine but the ws route doesn't.
Call to express from React app:
componentDidMount() {
let ws = new WebSocket('ws://localhost:3001/ws');
ws.on( 'open', function open() {
console.log('app connected to websocket!');
} );
ws.on( 'message', function ( message ) {
console.log( message );
})
}
I've looked at all the following questions and don't understand why their solutions don't work for me:
Socket.IO 404 Error
express-ws connection problem
Node not working with express-ws
If anyone can let me know what's going on that would be great.
It seems your code does not follow express-ws's document. To use express-ws and make WebSocket endpoint, the code would be as:
var express = require('express');
var app = express();
var expressWs = require('express-ws')(app);
...
app.ws('/', function(ws, req) {
ws.on('message', function(msg) {
console.log(msg);
});
console.log('socket running');
});
app.listen(3000);
In the client side, ws object does not have field on. To listen WebSocket connection and message, you can use onopen and onmessage:
ws.onopen = function() {
console.log('app connected to websocket!');
};
ws.onmessage = function(message) {
console.log( message );
};
I had this exact problem and for me the solution was to change:
server.listen(port);
to:
app.listen(port);
I suspect what is going on is that express-ws is using the app listen function as its cue to start upgrading connections to ws and this won't happen if the server listen port occurs instead.