cant connect flutter to node server localhost:3000 - node.js

function that gets triggered after button click in flutter. whenever i click the button, theres a connection error and nothing on the server side.
`void getTest() async {
BaseOptions options = BaseOptions(
baseUrl: "http://10.0.2.2:3000",
// connectTimeout: 1000,
// receiveTimeout: 3000,
);
Dio dio = Dio(options);
try {
Response resp = await dio.post(
options.baseUrl + "/test",
);
} catch (e) {
print("Exception: $e");
}
}`
code for node server. im running node server on localhost:3000
`const express = require('express');
const { Server } = require('ws');
const app = express();
app.get("/test", function(req, res){
console.log(req)
});
app.post("/test", function(req, res){
console.log(req)
});
app.listen(3000, function() {
console.log("Server started on port 3000");
});
`
debug console shows this error
`Exception: DioError [DioErrorType.connectTimeout]: Connecting timed out [0ms]`

Related

Socket connection is not working while using express with next.js

I have a problem with using socket.io in my application.
I use Next.js, Express.js, socket.io, socket.io-client
When I run Next.js server and Express server then access the page, socket is immediately connected. But when I post to /webhook/notify from other server socket.emit("notify", req.body); does not work. But when I reload the backend server, somehow it works for no reason.
Below are my codes
Frontend side
const socket = io.connect("http://127.0.0.1:3000", { cors: true }); //backend server
socket.on("connection", async (data) => { // it works
try {
console.log(data);
} catch (err) {
console.error(err.response);
}
});
socket.on("notify", async (notify) => { // it does not works while I reload backend server
try {
console.log(notify);
} catch (err) {
console.error(err.response);
}
});
Backend side
index.js
const app = express();
const PORT = process.env.PORT || 3000;
app.use(cors({ origin: "http://127.0.0.1:3060" }));
app.use(express.urlencoded({ extended: false }));
app.use(express.json());
const Socket = require("./socket");
const server = app.listen(PORT, function () {
return console.log("Backend server listening on port" + PORT);
});
Socket(server, app);
socket.js
const Socket = require("socket.io");
const axios = require("axios");
module.exports = (server, app) => {
const io = Socket(server, {
cors: {
origin: "*",
},
});
io.on("connection", (socket) => {
console.log("socket is connected");
app.post("/webhook/notify", (req, res, next) => {
try {
socket.emit("notify", req.body);
} catch (err) {
console.error(err.response);
return next(err);
}
});
socket.on("disconnect", () => {
console.log("disconnected");
});
});
};

xhr poll error in socketio react and node js application

I have a react app with a components
useEffect( () => {
const socket = io(process.env.REACT_APP_BACKEND_DEVELOPMENT_URL);
// dispatch( updateSocket({socket}) );
socket.on('connected' , async () => {
console.log( 'connected' );
});
socket.on("connect_error", (err) => {
console.log(`connect_error due to ${err.message}`);
});
},[])
And in node back end I have
var app = express();
const server = http.createServer(app);
const io = socketio( server , {
cors:{ origin: '*'},
});
io.on('connection', (stream) => {
console.log('someone connected!');
});
It is showing error 1. polling.js:334 GET http://localhost:4000/socket.io/?EIO=4&transport=polling&t=O3BfeYs 404 (Not Found)
2. Mainpage.jsx:78 connect_error due to xhr poll error
Tried to solve this by chaging transports option to 'websocket' (found in most troubleshooter ) doesn't worked well for me

Socket.IO and Electron can't emit or receive

I have an Electron project initiated with VueCLI and a litle nodejs socket.io server, here's the server's file :
const http = require('http');
const express = require('express');
const socketio = require('socket.io');
const {
userJoin,
getCurrentUser,
userLeave,
getRoomUsers,
users
} = require('./utils/users');
const app = express();
const server = http.createServer(app);
const io = socketio(server);
// Set static folder
app.use(express.static(path.join(__dirname, 'public')));
// Run when client connects
io.on('connection', socket => {
console.log(`Connected tp ${socket.id}`)
app.get('/send-file', (req, res, next) => {
res.send('Sent')
})
socket.on('joinRoom', (args)=>{
console.log('joinroom')
})
// Runs when client disconnects
socket.on('disconnect', () => {
const user = userLeave(socket.id);
});
});
const PORT = process.env.PORT || 7575;
server.listen(PORT, () => console.log(`Server running on port ${PORT}`));
And here's my preload.js file :
const io = require('socket.io-client');
window.socket = io('http://localhost:7575');
window.socket.on('welcome', () => {
console.log('on welcome : welcome received renderer'); // displayed
window.socket.emit('test')
});
window.socket.on('error', (e) => {
console.log(e); // displayed ?
});
window.socket.on('ok', () => {
console.log("OK received renderer"); // displayed
});
window.socket.on('connect', () => {
console.log("connected renderer"); // displayed
window.socket.emit('test');
});
And here's my createWindow function:
async function createWindow() {
// Create the browser window.
win = new BrowserWindow({
width: 700,
height: 600,
webPreferences: {
// Use pluginOptions.nodeIntegration, leave this alone
// See nklayman.github.io/vue-cli-plugin-electron-builder/guide/security.html#node-integration for more info
nodeIntegration: process.env.ELECTRON_NODE_INTEGRATION,
enableRemoteModule: true,
preload: path.join(__dirname, 'preload.js')
}
})
win.setMenu(null)
if (process.env.WEBPACK_DEV_SERVER_URL) {
// Load the url of the dev server if in development mode
await win.loadURL(process.env.WEBPACK_DEV_SERVER_URL)
if (!process.env.IS_TEST) win.webContents.openDevTools()
} else {
createProtocol('app')
// Load the index.html when not in development
win.loadURL('app://./index.html')
}
}
The connection is made between the client and the server, because the console.log(Connected tp ${socket.id}) show a different socket ID everytime, but on my compenent, when I call the emit function nothing happens : window.socket.emit('joinRoom', {email:this.email, apikey:this.apikey})
And I can't event receive message on the client side, I've tested the server and everything works fine on a normale browser, but on my electron application can't emit or receive messages.
Is this related to my electron application?
Here's how I did it -
Server side:
const express = require('express')
const app = express()
// middlewares
app.use(express.static('public'))
// routes
app.get('/', (req, res) => {
res.render('index')
})
server = app.listen(7575, () => {
console.log("Server started");
})
//socket.io instantiation
const io = require("socket.io")(server)
//listen on every connection
io.on('connection', (socket) => {
console.log('New user connected');
//listen on "test"
socket.on('test', (data) => {
var username = data.username;
})
})
Client side:
socket = io.connect('http://localhost:7575')
socket.emit('test', {username: 'username'})

Socket.io Node Js Server and React js Client not connecting

So first I would like to say that I have looked at many other answers that were given for similar questions, but none worked for me.
My setup is a node js server and a react js client. And I am having trouble doing just a basic setup. Any one who would help me out here, I really appreaciate.
And also on the client code I have alternated through different options for serverUrl from localhost with the http http://localhost:6000 and without localhost:6000. Same for ip address.
NODE JS Server Code
const express = require('express');
const app = express();
const users = require("./routes/api/users");
const profile = require("./routes/api/profile");
const project = require("./routes/api/project");
const auth = require("./routes/api/auth");
const email = require("./routes/api/email");
app.use(express.static(__dirname + '/public'));
const server = require('http').createServer(app);
const io = require('socket.io')(server);
io.on('connection', (socket)=> {
console.log("user connected")
socket.on('SEND_MESSAGE', function(data){
console.log("message received")
io.emit('RECEIVE_MESSAGE', data);
})
});
//*** Start of Routes ***//
app.use((req, res, next) => {
res.setHeader("Access-Control-Allow-Origin", "http://localhost:6000");
res.setHeader("Access-Control-Allow-Credentials", "true");
next();
})
app.use("/api/users", users);
app.use("/api/profile", profile);
app.use("/api/auth", auth);
app.use("/api/project", project);
app.use("/api/email", email);
//*** End of Routes ***//
const port = 6000;
server.listen(port, () => {
console.log(`Server Running at ${port}`);
});
REACT JS Client Code
import React,{useEffect,useState,useRef} from 'react';
import io from "socket.io-client";
class App extends React.Component {
constructor(props){
super(props);
this.state = {
username: 'name',
message: 'hello world',
messages: []
};
this.serverUrl = '127.0.0.1:6000';
this.socket = io(this.serverUrl, {reconnect: true});
this.setupSocket();
}
setupSocket() {
this.socket.on('connection', (data) => {
console.log(`Connected: ${data}`);
});
}
render(){
return(<p>Hello<p>)
}
}
export default App
It may have a problem with your socket server you can change your port and check if it is working

Start a nodejs tcp server within nodejs app

My use case to start and stop a tcp server within the nodejs app that i am writing.
So I have an index.js which starts up a web server on port 3000. Using endpoints '/' and '/start', i would like to get the status of the server and start the server respectively. I would also like to display the status of the server via socket.io but that's for later.
Right now, I am getting a
TypeError: Converting circular structure to JSON
error which I think it is probably attributable to returning the server object below.
How can I start and stop the tcp server via REST endpoints?
// server.js
'use strict'
var net = require('net')
var server = false
exports.get = function() {
return server
}
exports.start = function(port, host) {
if (!server) {
server = net.createServer(handleConnection).listen(port, host)
return server
}
}
exports.stop = function() {
if (server) {
server.close(() => {
console.log(`server.close called`)
})
server = null
return server
}
}
function handleConnection(socket) {
...
}
Here is the index.js
// index.js
'use strict'
var net = require('net')
var http = require('http')
var express = require('express')
var bodyParser = require('body-parser')
var app = express()
var addServer = require('./server')
var PORT = 3000
var HOSTNAME = '127.0.0.1'
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: true }))
var server = http.createServer(app).listen(PORT, HOSTNAME, () => {
console.log('http.createServer started')
})
app.get('/', (req, res) => {
// get addServer status
addServer.get()
res.status(200).json({ status: 'success', command: addServer.get() })
})
app.get('/start', (req, res) => {
// start addServer
addServer.start(9000, '127.0.0.1')
res.status(200).json({ status: 'success', response: '' })
})
You're trying to return server object via json.
res.status(200).json({ status: 'success', command: addServer.get() })
Try without it.
res.status(200).json({ status: 'success' })

Resources