Android 应用程序无法连接到 Socket.io 服务器

时间:2021-03-13 23:36:58

标签: java android node.js sockets socket.io

我正在用 tuple 中的 Socket.io 制作一个基本的实时聊天应用。

我创建了一个服务器和应用程序,但应用程序似乎没有连接到服务器。

这是我试过的代码:

server.js

Node.js

客户端java代码:

const app = require('express')();
const http = require('http').createServer(app);
const io = require('socket.io')(http);
var port=8080;


app.get('/', function(req, res){ 
 res.sendFile(__dirname+'/index.html');
});


io.on('connection', (socket) => {
  io.emit('msg','joined');
socket.on('msg', (msg) => {
    io.emit('msg', msg);
        console.log(msg);
  });

});


http.listen(port, () => {
  console.log('Listening: '+port);
});

所以当我打开应用程序时,它显示“未连接”,因为只有当应用程序无法连接到服务器时才会执行此操作。

logCat 多次只添加这一行: import com.github.nkzawa.socketio.client.Socket; import com.github.nkzawa.socketio.client.IO; ... String server="http://0.0.0.0:8080/"; private Socket sock; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); try{ sock=IO.socket(server); }catch(URISyntaxException e){} sock.connect(); if(sock.connected()){ toast("Connected"); }else{ toast("Not connected"); } //always showing not connected }

注意: 我在我的 android 设备上使用 termux 托管 Node.js。(它在浏览器上运行良好)。也是我用来使用 Android IDE 应用程序创建应用程序的同一 Android 设备。

0 个答案:

没有答案