When in development env, this works as expected, Server Code... In development, I only specify the url in the client as const socket = io("http://localhost:3001"); Below is the server code.
const httpServer = createServer(app);
export const io = new Server(httpServer, {
cors: {
origin: "*",
},
path: "/socket.io/",
});
io.on("connection", (socket) => {
// make function calls
postOrderDeliveryStatus(socket);
// getOrders(socket);
// console.log("Socket Connected");
// close socket
socket.on("disconnect", () => {
socket.disconnect(true);
});
});
httpServer.listen(3001);
//mongoose
// console.log(process.env.CONNECTION_URL)
mongoose
.connect(process.env.CONNECTION_URL, {
useNewUrlParser: true,
useUnifiedTopology: true,
useCreateIndex: true,
})
.then(() =>
app.listen(PORT, () =>
winston.info(
`Server Running in ${process.env.NODE_ENV} mode on Port: ${PORT}`
)
)
)
.catch((error) => console.log(`${error} did not connect`));
mongoose.set("useFindAndModify", false);
Client...
const socket = io("http://localhost:3001");
const dispatchOrderHandler = () => {
const delivery_status = "DISPATCHED";
socket.emit("update-order", order._id, delivery_status);
// dispatch(getOrderDetailsToProcess(paramsOrderId)); //This dispatch alone can suffice
socket.on("updated-order", (updated_order) => {
dispatch(
getOrderDetailsToProcess(paramsOrderId, (order) => [
...order,
updated_order,
])
);
});
};
The error i get when sockets run is net::ERR_CONNECTION_REFUSED. I also tried const socket = io(); without specifying the url since both the client and the server run on the same domain but that didn't either? What should the connection URL be in production since specifying the domain name hasn't worked? Am using heroku!
When using a hosting service, the service will provide the port to the client. You can access that port through
process.env.PORT. To make the experience a bit more friendly to yourself as a developer, you can listen to the port usinghttpServer.listen(process.env.PORT || 3001);As for the client, I believe you are right on using
const socket = io();, although I haven't used socket.io in a while.