Javascript 套接字不适用于使用ws的React native和Node.js服务器
我正在尝试使用套接字将我的后端(node.js服务器)连接到前端(react native app)。 但问题是代码永远不会进入io.on('connection',…)。 i、 e.未建立插座连接 感谢您的帮助 这是客户端代码:Javascript 套接字不适用于使用ws的React native和Node.js服务器,javascript,node.js,sockets,react-native,Javascript,Node.js,Sockets,React Native,我正在尝试使用套接字将我的后端(node.js服务器)连接到前端(react native app)。 但问题是代码永远不会进入io.on('connection',…)。 i、 e.未建立插座连接 感谢您的帮助 这是客户端代码: import React, { Component } from 'react'; import { Alert, Button, Text, View } from 'react-native'; export defau
import React, { Component } from 'react';
import {
Alert,
Button,
Text,
View
} from 'react-native';
export default class App extends Component {
constructor(props) {
super(props);
const ws = new WebSocket('ws://localhost:3000');
console.log("This is client side Web socket.")
ws.onopen = () => {
console.log("Its connected")
ws.send('something'); // send a message
};
}
}
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
io.on('connection', function(socket){
console.log('a user connected');
});
http.listen(3000, function(){
console.log('listening on *:3000');
});
这是服务器端代码:
import React, { Component } from 'react';
import {
Alert,
Button,
Text,
View
} from 'react-native';
export default class App extends Component {
constructor(props) {
super(props);
const ws = new WebSocket('ws://localhost:3000');
console.log("This is client side Web socket.")
ws.onopen = () => {
console.log("Its connected")
ws.send('something'); // send a message
};
}
}
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
io.on('connection', function(socket){
console.log('a user connected');
});
http.listen(3000, function(){
console.log('listening on *:3000');
});
安装npm模块
socket.io客户端
,然后重试
import React, {
Component
} from 'react';
import {
Alert,
Button,
Text,
View
} from 'react-native';
import SocketIOClient from 'socket.io-client';
export default class App extends Component {
constructor(props) {
super(props);
var ws = SocketIOClient('ws://localhost:3000'); // replace localhost with ip
ws.on('connect', function() {
console.log("hello");
});
}
}
哦,我刚刚发现了问题。它适用于IOS,但不适用于Android。你能帮我一下吗?更换你的本地主机ip然后检查。。在我的Android和iOS设备中,将本地主机更改为ip有效!非常感谢。虽然我无法理解为什么会发生这种事@嗨,你能看看我的问题吗。