【发布时间】:2017-10-17 02:07:40
【问题描述】:
我的 react native 一直说 [Error: websocket error]。我在网上遵循了一些教程,但仍然无法正常工作。任何人都知道这段代码是否存在语法错误或需要更改的内容?
这是我从这个主题 socket io not working 遵循的完整反应代码
ReactNative 代码:
import React, {Component} from 'react';
import {
View,
Text,
TouchableOpacity,
AsyncStorage,
StyleSheet
} from 'react-native';
const io = require('socket.io-client');
export default class App extends Component{
constructor(props){
super(props);
this.componentDidMount = this.componentDidMount.bind(this);
this.onPress = this.onPress.bind(this);
}
componentDidMount () {
const socket = io('http://localhost:3000', {
transports: ['websocket']
})
socket.on('connect', () => {
console.log("socket connected")
socket.emit('YOUR EVENT TO SERVER', {})
socket.on('EVENT YOU WANNA LISTEN', (r) => {
})
})
socket.on('connect_error', (err) => {
console.log(err)
})
socket.on('disconnect', () => {
console.log("Disconnected Socket!")
})
}
onPress(){
// socket.emit('message', {data: 'data'});
}
render() {
return (
<View style={{alignItems: 'center', padding: 20}}>
<Text>SOCKET IO</Text>
<TouchableOpacity
style={{backgroundColor: '#EEE', height: 50, width: 200, borderColor: 'black', alignItems: 'center', padding: 15}}
onPress={()=>this.onPress()}
>
<Text>CLICK</Text>
</TouchableOpacity>
</View>
);
}
}
在我的情况下使用这个 const io = require('socket.io-client/socket.io'); 不起作用
这是我对 package.json 的依赖
"dependencies": {
"react": "16.0.0-alpha.6",
"react-native": "0.44.0",
"socket.io-client": "^2.0.1"
},
"devDependencies": {
"babel-jest": "20.0.1",
"babel-preset-react-native": "1.9.2",
"jest": "20.0.1",
"react-test-renderer": "16.0.0-alpha.6"
},
【问题讨论】:
-
你有本地套接字服务器在运行吗?
-
查看实际socket错误,使用console.logs检测
-
这是 console.log 产生的 imgur.com/4KxgvSQ
-
刚才我的笔记本电脑通过 wify 连接。我将我的本机应用程序连接到 IP 192.168.3.110,它已连接。所以只有当我的笔记本电脑连接到 wify 网络时才连接。 io('192.168.3.110:3000', {transport:['websocket']})
-
你试过用
ws://localhost:3000代替http://localhost:3000