反应本机和 socket.io 节点不工作 [英] React native and socket.io node not working

查看:45
本文介绍了反应本机和 socket.io 节点不工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面是我试图连接到我的节点 websocket 后端的我的本机组件和节点 server.js 代码.

Below is my react native component and node server.js code that I am trying to connect to my node websocket backend.

我的反应代码与服务器在同一台计算机上运行.我在这里和 github 上找到了很多不同的答案,但我都无法使用.

My react code is running on the same computer as the server. I have found so many varying answers on here, and github, none of which I can get working.

我还发现了这个问题从未回答,这个问题有一个回答,我无法工作(一年多前被问到)

I also found this question which was never answered, and this question has an answer, which I cannot get working (was asked over a year ago)

我找到了这篇文章 并尝试根据这些指南修改我的代码,但这没有用.

I have found this article and tried to amend my code based on these guidelines but this did not work.

反应代码

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

const io = require('socket.io-client/socket.io');
let socket = io('http://localhost:3000');

export default class App extends React.Component {

    constructor(props) {
        super(props);
        console.log(socket);
    }

    render() {
        return (
            <View>
                <Text>Websocket</Text>
            </View>
        );
    }
}

server.js

const express = require('express');
const http = require('http')
const socketio = require('socket.io');

const app = express();
const server = http.Server(app);
const websocket = socketio(server);
server.listen(3000, () => console.log('listening on *:3000'));

console.log(websocket)

// The event will be called when a client is connected.
websocket.on('connection', (socket) => {
  console.log('A client just joined on', socket.id);
});

我正在使用以下版本的软件包

I am using the following versions of packages

"expo": "^16.0.0",
"react": "16.0.0-alpha.6",
"react-native": "^0.43.4",
"socket.io-client": "^1.7.3"

推荐答案

我认为应该是

const io = require('socket.io-client');

哪个对我有用.

我记得在使用 React Native 时遇到过这类问题.许多 socket.io 教程(包括他们页面上的教程)假设您使用的是通过 HTML 文档中的脚本标签导入 JS 的旧样式.看起来 socket.io 改变了命名空间,因为我记得它是 socket.io-client/socket.io 前段时间,如果有内存的话......

I remember running into these sorts of issues when using react native. A lot of socket.io tutorials (including the one on their page) assume you're using an older style of importing JS via script tags in an HTML doc. It looks like socket.io changed the namespace as I do remember it being socket.io-client/socket.io some time ago if memory serves...

这篇关于反应本机和 socket.io 节点不工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆