Laravel Websockets + React Native

pftdvrlh  于 2023-06-06  发布在  React
关注(0)|答案(1)|浏览(304)

我无法从ReactNative应用程序连接到Laravel的WebSocket。我几乎尝试了所有包含“pusher”,“websockets”或类似单词的npm包,但它们都不起作用,我开始感到绝望。
例如,我在package.json文件中堆叠了几个包,例如:

"react-native-use-websocket": "^0.2.6",
"react-native-websocket": "^1.0.2",
"laravel-echo": "^1.15.0",
"pusher-js": "^8.0.1",
// No one worked for me following the oficial docs...

...是否有人有可以以任何方式工作的配置?我真想把电脑扔出窗外。
在Laravel中,一切正常,也就是说,启动WebSocket服务器并使用Tinker进行测试,我可以在“www.example.com”上完美地看到http://127.0.0.1:8000/laravel-websockets消息是如何发送的,但在React应用程序中,我甚至无法接近。
有人能帮帮我吗?
Laravel配置(完美的工作是:)

  • env
BROADCAST_DRIVER=pusher
//...
PUSHER_APP_ID=12345
PUSHER_APP_KEY=ADDADD123123
PUSHER_APP_SECRET=ADASADAS123123
PUSHER_HOST=127.0.0.1
PUSHER_PORT=6001
PUSHER_SCHEME=http
PUSHER_APP_CLUSTER=mt1
  • NewMessage.php
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;

class NewMessage implements ShouldBroadcast
{
    use Dispatchable, InteractsWithSockets, SerializesModels;

    public $message;
    /**
     * Create a new event instance.
     */
    public function __construct($message)
    {
        $this->message = $message;
    }

    /**
     * Get the channels the event should broadcast on.
     *
     * @return array<int, \Illuminate\Broadcasting\Channel>
     */
    public function broadcastOn()
    {
        // return [
        //     new PrivateChannel('channel-name'),
        // ];
        return new Channel('home');
    }
}

我不能显示我的React代码,因为没有一个选项以任何方式工作。我只是想能够看到消息,第一次连接,最低限度的hello world。但不可能除了开枪自杀我还有什么选择
如果我试着这样:

import Pusher from 'pusher-js/react-native';
import { SafeAreaView } from 'react-native-safe-area-context';

const PusherTest = () => {
  const [message, setMessage] = useState([]);
  useEffect(() => {
    const pusher = new Pusher('ADDADD123123', {
      cluster: 'mt1',
      encrypted: true,
      wsHost: '127.0.0.1',
      wsPort: 6001,      
    });

    const channel = pusher.subscribe('home');

    channel.bind('App\\Events\\TestEvent', (data) => {
      console.log('Received event:', data);
      setMessage(data);
    });

    return () => {
      pusher.disconnect();
    };
  }, []);

  return (
    <SafeAreaView>
      <Text>Hi</Text>
      <Text>{message}</Text>
    </SafeAreaView>
  )
};

export default PusherTest;

我得到一个错误,它说:

ReferenceError: Can't find variable: Buffer

这是一个npm包错误,不是我的。让我们试试另一种方法:
让我们试试socket.io:

import React, { useState, useEffect } from 'react';
import { Text } from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import { io } from 'socket.io-client';

const SOCKET_SERVER_URL = 'http://localhost:6001'; // URL del servidor de WebSocket

const WebSocketTest = () => {
    const [messages, setMessages] = useState([]);

    useEffect(() => {
        const socket = io(SOCKET_SERVER_URL);
        
        socket.on('connect', () => {
            console.log('Conectado al servidor de WebSocket');
        });

        socket.on('disconnect', () => {
            console.log('Desconectado del servidor de WebSocket');
        });

        socket.on('message', (data) => {
            console.log('Mensaje recibido:', data);
            setMessages((messages) => [...messages, data]);
        });

        return () => {
            socket.disconnect();
        };
    }, []);

    return (
        <SafeAreaView>
            <Text>Hi</Text>
            {messages.map((message, index) => (
                <Text key={index}>{message}</Text>
            ))}
        </SafeAreaView>
    );
};

export default WebSocketTest;

我没有得到任何响应,并且在文档中找不到要在哪里分配我想要订阅的频道的名称。

bq3bfh9z

bq3bfh9z1#

我可以通过使用laravel-echo包来实现这一点。我在Echo选项中定义了Pusher示例(因为在react native中,您不能通过将其分配给window来设置全局Pusher示例)。这是我使用的基本实现。

import Pusher from 'pusher-js'
import Echo from 'laravel-echo'

export default const Echo = new Echo({
    broadcaster: 'pusher',
    Pusher, // sets the instance imported above

    // Tweak the options according to your settings
    key: '', // set the key defined in your .env
    wsHost: 'localhost', // the host defined in your .env
    wssHost: 'localhost', // the host defined in your .env
    wsPort: 6001, // or the port defined in your .env
    wssPort: 6001, // or the port defined in your .env
    forceTLS: false,
    encrypted: false,
    cluster: 'mt1',
    enabledTransports: ['ws', 'wss],
})

然后你可以像在Laravel前端一样监听事件。

import Echo from '/path/to/above/file';
import {useEffect} from 'react';

function YourComponent({yourProps}) {
  // your hooks and functions...

  useEffect(()=>{
    Echo.channel('your-channel')
      .listen('YourEventName', (eventData) => {
        // do something when the event fires
      });
  },[])

  return (<>{/* Your Component */}<>)
}

相关问题