socket.io 无法从移动浏览器连接



我正在尝试创建一个网络应用程序,玩家可以在其中加入游戏,他们的名字将显示在主板视图上。我正试图通过使用socket.io.的React和Node.js+express来实现这一点

目前,当玩家提交他们的信息时,我会向Node服务器发送一个事件,并将他们的信息推送给一组连接的用户。然后通过API请求返回此数组。我的实现可以在桌面浏览器(Chrome、Firefox等(中正常工作,但我无法使用移动浏览器(在本例中,是Android上的Chrome(打开socket.io连接。

在这两种情况下,我都通过导航到http://111.111.1.66:3000/(React应用程序在端口3000上运行(。我在所有设备上都连接到同一网络,并且可以在所有浏览器(包括手机(上查看/导航我的应用程序。

当客户端连接时,我会在服务器中记录一条"用户连接"消息。我可以从桌面浏览器中看到它正常工作,但在尝试连接手机时不会记录任何消息。类似地,尝试从移动浏览器提交玩家信息不会引发事件。

相关代码如下:

客户端(即玩家提交信息的视图(:

import React, { Component } from 'react';
import socketClient from 'socket.io-client';
class PlayerJoin extends Component {
constructor(props) {
super(props);
const socket = socketClient('http://localhost:5000');
this.state = {
socket,
name: null,
};
}
handleChange = (e, field) => {
...collapsed...
}
handleSubmit = () => {
const { socket, name } this.state;
const payload = {
name,
};
socket.emit('playerJoin', payload);
}
render() {
return (
<form className="playerForm">
<input className="nameInput" onChange={(e) => this.handleChange(e, 'name')} placeholder="Enter name" autoFocus type="text" />
<button type="button" onClick={this.handleSubmit}>Submit</button>
</form>
);
}
}

服务器:

var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
const users = [];
app.get('/getPlayers', function(req, res){
res.send(JSON.stringify(users));
});
io.on('connection', (socket) => {
console.log('a user connected');
socket.on('playerJoin', (player) => {
users.push(player);
socket.broadcast.emit('listUpdate', users); // the main view listens for this event
});
});
http.listen(5000, () => {
console.log('listening on port 5000');
});

尝试更改此

const socket = socketClient('http://localhost:5000');

const socket = socketClient('http://<ip_of_device_where_your_node_server_is_running>:5000');

client-side:上

const socket = socketClient(
'http://<ip_of_device_where_your_node_server_is_running>:5000'
);

您还必须修改服务器端通过将localhost替换为:ip_of_device_where_your_react_server_is_running>:port

最新更新