繁体   English   中英

在真正的 android 设备上运行时,Ionic 4 android 应用程序未连接到本地节点 js 服务器

[英]Ionic 4 android app not connecting to local node js server when running on real android device

我正在尝试为我的 Ionic 4 android 应用程序实现客户端-服务器通信。 我的电脑上有一个本地节点 js 服务器实现,我正在使用 socket.io 建立通信。 问题是,当我在浏览器或模拟器上运行应用程序时,应用程序和本地服务器之间的通信正常,但是当我尝试在真正的 android 设备(三星 Galaxy s9+)上运行应用程序时,应用程序无法连接到本地服务器。 更具体地说,服务器控制台上没有出现消息“用户已连接”,以指示应用程序已连接到服务器,因此用户永远不会取回他的用户 ID。

谁能帮我找出原因?

服务器端

索引.js

let app = require('express')();
let server = require('http').createServer(app);
let io = require('socket.io')(server);

// Allow CORS support and remote requests to the service
app.use(function(req, res, next)
{
  res.setHeader('Access-Control-Allow-Origin', '*');
  res.setHeader('Access-Control-Allow-Methods', 'GET, POST');
  res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type,Authorization');
  next();
});

// Set up route 
app.get('/', (req, res) =>
{
  res.json({ message: 'You connected to panic Shield server' });
});

var port = process.env.PORT || 8080;

server.listen(port, function(){
  console.log('listening in http://192.168.x.x:' + port);
});

const uuidv4 = require("uuid/v4");

// User connected to the server
io.on('connection', (socket) => {

  console.log('User Connected');

  socket.on('disconnect', function(){});

  socket.on('set-credentials', (credentials) => {
    let userId = uuidv4();
    ...
    // server informs user for his unique id
    socket.emit('your user id', userId);
    ...
  }
});

客户端

app.module.ts

import { SocketIoModule, SocketIoConfig } from 'ngx-socket-io';
const config: SocketIoConfig = { url: 'http://192.168.x.x:8080', options: { secure: true } };

@NgModule({
  declarations: [AppComponent],
  entryComponents: [],
  imports: [
    BrowserModule,
    IonicModule.forRoot(),
    AppRoutingModule,
    HttpClientModule,
    SocketIoModule.forRoot(config)
],
...

主页.ts

import { Socket } from 'ngx-socket-io';

constructor(private socket: Socket) { }

async ngOnInit() {
  this.socket.connect();
  ...
}

async connectToServer(name, surname, gender, speech) {
  const str = name.concat(' // ').concat(surname).concat(' // ').concat(gender).concat(' // ').concat(speech);
  this.socket.emit('set-credentials', str);
  this.socket.on('your user id', (data) => {
    this.userId = data.toString();
    // save the userId
    set('userId', this.userId);
    // Refresh the page
    window.location.reload();
  });
}

我发现了问题。 就我而言,我电脑的防火墙不允许本地网络上的任何其他设备连接到服务器。 当我关闭防火墙时,客户端-服务器之间的连接就建立了!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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