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