简体   繁体   中英

I keep getting 404 error in socket.io connection

I am trying to connect my android app to NodeJS server.

ANDROID PART

First I include the Socket.io library to my dependency

implementation('io.socket:socket.io-client:2.0.0') {
    exclude group: 'org.json', module: 'json'
}

My JAVA code

//all variables used are initialized, defined and working perfectly
try {
    socket = IO.socket(socketUrl);
    socket.on(Socket.EVENT_CONNECT, args -> runOnUiThread(() -> socket.emit("connected", true)));
    socket.connect();
} catch (URISyntaxException e) {
    e.printStackTrace();
}

SERVER SIDE

var express = require('express'),
app = express(),
socket = require('socket.io'),
router = express.Router();

router.get('/', function(req, res, next) {
  res.render('index', { title: 'Express' });
});

var server = app.listen(4000, function(){
    console.log('listening for requests on port 4000,');
});

let io = socket(server);

io.on('connection', function(socket){
  console.log(`${socket.id} is connected`);
});

module.exports = router;

Now the problem is after starting the Server, and I try to connect my android app to it, I keep getting an error from Socket.io connection, like the image below

错误图像

I have searched SO for solution and I get multiple answers relating to this, but I still keep getting the same error

My Socket.io version is 8.5.5

you can not use socket directly via express, here is the documentation.

try this code instead.

var express = require('express'),
app = express()
const httpServer = require("http").createServer(app);
const io = require("socket.io")(httpServer);


router = express.Router();

router.get('/', function(req, res, next) {
  res.render('index', { title: 'Express' });
});

io.on('connection', function(socket){
  console.log(`${socket.id} is connected`);
});

httpServer.listen(4000, function(){
    console.log('listening for requests on port 4000,');
});


module.exports = router;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM