gpt4 book ai didi

javascript - 使用 WebSocket 的 React Native 不起作用

转载 作者:搜寻专家 更新时间:2023-10-31 23:41:09 25 4
gpt4 key购买 nike

我听说 Socket.io 在 React Native 中不能正常工作,所以我决定改用普通的 WebSocket。

我正在使用 node.js 来实现 WebSocket 服务器,这并不难。对于浏览器,我尝试的所有方法都有效,但对于 React Native,没有成功。

这些是我尝试实现 websocket 服务器的方法:

  • express -ws
  • ws

express-ws 在没有任何错误消息的情况下无法正常工作。只是它说无法连接某些东西。

所以我把模块改成了ws,这个模块应该是客户端和服务端都需要的,所以我就这么做了。服务器工作正常,但是在 AVD 上使用 android 的应用程序中时,它说:

Requiring unknown module "url".If you are sure the module is there, try restarting the packager or running "npm install".

所以我完全删除了 node_modules 目录并重新安装它们,但同样的错误再次出现。

我正在使用 Node v6.2.2 和 react-native-cli 1.0.0,react-native 0.33.0。

这是带有 ws 模块的服务器代码(与 ws 模块自述文件相同):

var WebSocketServer = require('ws').Server;
var wss = new WebSocketServer({ port: 3000 });

wss.on('connection', (socket) => {
socket.on('message', (msg) => {
console.log('Received: ' + msg);
});

socket.send('something');
});

这是客户:

import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
View
} from 'react-native';

const WebSocket = require('ws');

class wschat extends Component {
constructor() {
super();
}
componentDidMount() {
var socket = new WebSocket("ws://localhost:3000");

socket.on('open', () => {
socket.send('something');
});
socket.on('message', (data, flags) => {
console.log(data);
console.log(flags);
});
}
...

为了避免命名冲突,我在需要 ws 模块时使用了 WebSock 而不是 WebSocket,但这不是问题。

我错过了什么吗? React Native 文档没有太多解释,也很难找到工作示例。感谢阅读,如有任何建议,我们将不胜感激。

最佳答案

最新的react native支持websocket,所以我们不必依赖第三方websocket客户端库。

以下示例基于react native 0.45,工程由create-react-native-app生成。

import React, {Component} from 'react';
import {Text, View} from 'react-native';

export default class App extends React.Component {

constructor() {
super();

this.state = {
echo: ''
};
}

componentDidMount() {
var socket = new WebSocket('wss://echo.websocket.org/');

socket.onopen = () => socket.send(new Date().toGMTString());

socket.onmessage = ({data}) => {
console.log(data);

this.setState({echo: data});

setTimeout(() => {
socket.send(new Date().toGMTString());
}, 3000);
}
}

render() {
return (
<View>
<Text>websocket echo: {this.state.echo}</Text>
</View>
);
}
}

关于javascript - 使用 WebSocket 的 React Native 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39728000/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com