Recently I was trying to implement React Native chat with Laravel Websocket and I couldn't find any guide or help. So I thought, I will document the process i used to implement it.
Laravel Websocket is a fantastic package by BeyondCode which can be used to setup a simple websocket server on top a laravel project. This project can also be used a Drop-in Pusher replacement. You can read the documentation and details from their site.
Please for the guide in their documentation to install the package. After installing you should get an APP_KEY, APP_SECRET, WEBSOCKET_URL and WEBSOCKET_PORT. Then follow the steps below.
Since this is a drop-in pusher replacement, we can user Pusher packages. So first install pusher-js package to react native application.
npm install --save pusher-js
Create pusher client wrapper file
import Pusher from 'pusher-js/react-native';
let APP_KEY = '1234567890'
let AUTH_URL = 'service.example.com'
let WEBSOCKET_URL = 'websocket.example.com'
let WEBSOCKET_PORT = '6001'
export default (token) => {
let options = {
encrypted: false,
key: APP_KEY,
wsHost: WEBSOCKET_URL,
wsPort: WEBSOCKET_PORT,
disableStats: true,
authEndpoint: AUTH_URL + 'broadcasting/auth',
forceTLS: false,
auth: {
headers: {
'Authorization': 'Bearer ' + token,
},
}
};
return new Pusher(options.key, options);
};
Import the client wrapper and subscribe to the channels
import PusherClient from '../PusherClient';
let user = await AsyncStorage.getItem('user');
let token = await AsyncStorage.getItem('token');
let pusher = new PusherClient(token);
var channel = pusher.subscribe(`messages.${user}`);
channel.bind('App\\Events\\Message',
(data) => {
console.log(data)
}
);
Remember to append private- if you are listening to private message.
var channel = pusher.subscribe(`private-messages.${user}`);
channel.bind('App\\Events\\Message',
(data) => {
console.log(data)
}
);
Hope this helps anyone looking to implement this. Thanks.