A list of puns related to "WebSocket"
Hey guys. I need to configure Laravel WebSocket over HTTPS in production but I struggle to find a secure way. Could someone give me their configuration file (+ the js code where you connect to the WebSocket) so I can check if I am doing everything right?
Beside that, what permissions have you set to privkey and fullchain? The websocket is run by a user "laravel" who owns the site in my case.
Hi everyone,
I made a screencast about building a real time chat app using a WebSocket (running on lambda + API Gateway) https://www.youtube.com/watch?v=BcWD-M2PJ-8
And published the source code on github:
the lambda code: https://github.com/alexkrkn/lambda-websocket-server
the reactjs client: https://github.com/alexkrkn/lambda-websocket-client
I hope someone finds it useful and I'd appreciate any feedback.
Thanks!
Hi all, I was looking through the wiki and noticed the wait time workaround that was used to get around a websocket bug with WINE. I saw that there are a few people that are saying that this is now fixed on wine-staging and both of the bugs appear to be fixed. Does this mean that this artificial wait time is no longer necessary or am I missing something? If it has been fixed does this mean that launch times could be improved a bit or is there still other things that are preventing faster launch times?
I also just want to say its not a huge inconvenience at all I'm just wondering if we can improve the experience for everyone!
The game won't launch cause of this error, I played until 1 hour ago when I closed because the servers were on fire. Any idea on how to solve??
We are having an issue using real-time apps through WebSockets on Chromebooks. The app works on phones, iPads, and PCs (even using the Chrome browser). The only failed transports are on Chromebooks (https://nearpod.com/connectors/socket).
Has anyone successfully resolved a similar issue on Chromebooks?
In terms of CPU + RAM usage of and network traffic to the RPC node, which approach uses fewer resources? Polling periodically to get account updates or opening a websocket connection using onAccountChange? At what polling frequency / # websockets opened does it make sense to switch to the other approach to be nicer to the RPC node?
A bit of foreground is that I'm working on a full-stack web application built with a node backend and a Next frontend. I'm developing chat functionality hence I decided on WebSockets to be able to receive real-time updates from the server.
Now, while I'm developing my application, I realized I not only need an event-driven API that Web sockets is so great for. I also need a more "traditional" transactional request/response pattern. To be very specific I need the event-driven approach to inform clients about new messages, but I need to be able to request the server to post a new message in the chat. And I would like to be able to get acknowledgment from the server that the message has indeed been posted(or not). And this is just one example, but there is of course more.
Most examples online are very simple and only implement the necessary functionality to demo the capabilities of Websockets. And not how to handle the less obvious requirements that a real-world system might have. So I'm in doubt about how to design my system.
My current idea is to have the backend that has both WebSocket connections to the client and provides REST endpoints for any req/res actions. I believe this is valid, especially because I realize that this is how GraphQL(and therefore fx. messenger) works with API that utilizes Subscriptions for real-time events and has mutations/queries for req/res type actions.
BUT I'm not using GraphQL, so I don't find much information about this type of backend. So I'm in doubt if there are any major drawbacks to designing a backend like this. The alternative I see is of course to implement a req/res pattern on top of the WebSocket connection. But that would require some engineering, which I would be without if I just used the normal REST pattern I've worked with many times before.
TL;DR: I'm looking for advice on whether it makes sense to have both a WebSocket connection and REST API endpoints in the same backend for the same application. Because I need both capabilities from an event-driven API as well as a "traditional" request/response-based API.
Here is a typical template for a WebSocket server on node.
var WebSocketServer = require('websocket').server;
var http = require('http');
var server = http.createServer(function(request, response) {
// process HTTP request. Since we're writing just WebSockets
// server we don't have to implement anything.
});
server.listen(1337, function() { });
// create the server
wsServer = new WebSocketServer({
httpServer: server
});
// WebSocket server
wsServer.on('request', function(request) {
var connection = request.accept(null, request.origin);
// This is the most important callback for us, we'll handle
// all messages from users here.
connection.on('message', function(message) {
if (message.type === 'utf8') {
// process WebSocket message
}
});
connection.on('close', function(connection) {
// close user connection
});
});
Let's say that my node server receives (or self generates) non WebSocketServer events that require it to send messages to the client without first receiving a message from the client. How does one send data to the client in such a case?
Example: my node server receives regular socket UDP messages (not WebSocket messages) from another client 10x a second. I want to repackage those messages and send them to the client (running in a browser) without the browser client asking for them first.
Specifically, what object (of the websocketServer ?) does the send come from ? I assume it would be 'connection', but how does one obtain the connection object outside of responding to the websocketserver event from the browser client?
For example:
//send a message every second
var messageCount = 1;
function sendMessage()
{
wsServer.sendMessage("This is a test.");
//wsServer.send("Message #" + messageCount);
messageCount++;
}
let timer = setInterval(() => sendMessage(),1000);
This results in the error message "TypeError: wsServer.send is not a function" or "TypeError: wsServer.sendMessage is not a function". This makes sense because there is no WebSocketServer send function, only for WebSocket. Do I create a WebSocket on the same http socket and use it to send ?
Thanks.
Solved: I ended up going with the original tungstenite
crate. Configuring the TCP socket to be non-blocking helps the Macroquad game run smoothly.
On my server, I used Tokio for websockets. I tried implementing it on my Macroquad game client as well, but I have discovered that they are incompatible because Tokio is a multi-threaded runtime, while Macroquad is single-threaded so that it can work with WASM. There are some workarounds provided at the link, but I would prefer to use another capable websockets crate if possible.
There is a chart of rust websocket crates, but I am not sure how to determine which ones would be compatible with macroquad.
Which WebSockets crate is best to use with Macroquad?
Edit: Just discovered web-sys
in Rustβs wasm-bindgen
crate. It seems like it could work well with Macroquad but I have not tried implementing it yet.
Hello everybody, I'm trying to use laravel-websockets wich implements pusher server but for some reason I can't listen to events even though I can see the events in laravel websockets dashboard and in console.
https://github.com/beyondcode/laravel-websockets
"beyondcode/laravel-websockets": "^1.12",
"pusher/pusher-php-server": "^5.0"
"laravel-echo": "^1.11.3",
"pusher-js": "^7.0.3",
In client( I'm using ngrok since I'm testing on local machine):
This is how I setup Pusher client and echo, I'm not receiving any alert:
//BASE_URL = https://9fa8-88-5-254-23.ngrok.io
const startPusherChatServerBetter = () =>
{
Pusher.logToConsole = true;
let options = {
key: env.PUSHER_APP_KEY,
wsHost: env.BASE_URL,
wsPort: '6001',
wssPort: '6001',
disableStats: true,
logToConsole: true,
encrypted: false,
enabledTransports: ['wss','ws'],
};
let PusherClient = new Pusher(options.key, options);
PusherClient.connection.bind( 'error', () => console.log('PusherClient::error', arguments))
const echo = new Echo({
broadcaster: 'pusher',
client: PusherClient,
...options
});
echo.channel('chat').listen('MessageSent', (e) => {
Alert.alert('RECEIVED');
})
.listenForWhisper('typing', (user) => {
console.log('An user is typing...');
});
};
In backend:
How I fire event:
broadcast(new MessageSent($message))->toOthers();
My event:
<?php
namespace App\Events;
use Illuminate\Broadcasting\Channel;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Broadcasting\PresenceChannel;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use Illuminate\Contracts\Broadcasting\ShouldBroadcastNow;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;
use App\Models\User;
use App\Models\Message;
class MessageSent implements ShouldBroadcastNow
{
use Dispatchable, InteractsWithSockets, SerializesModels;
public $message;
/**
* Create a new event instance.
*
* @return void
*/
public function __construct(Message $message)
{
$this->message = $message;
}
/**
* Get the channels the event should broadcast on.
*
* @return \I
... keep reading on reddit β‘Hi, I'm new to ReactJS
I am trying to make a dashboard that checks the status of a device. I get this status from the api, so I need a way to make the dashboard to be always aware of any change in the status. I have heard that websockets are used in these cases, but researching I have seen that they work with a server and not with a rest api. Is there any way to use websockets with the api or is it better to use another technology?
I've been beating my head against the wall trying to figure out how to send a WebSocket message with PowerShell Core 7.2.1. I'm using the built-in ClientWebSocket
class.
$ErrorActionPreference = 'stop'
$WebSocket = [System.Net.WebSockets.ClientWebSocket]::new()
$Uri = 'ws://127.0.0.1:34001/wsclients'
$Token = [System.Threading.CancellationToken]::new($false)
$ConnectTask = $WebSocket.ConnectAsync($Uri, $Token)
while (!$ConnectTask.IsCompleted) {
Start-Sleep -Milliseconds 100
}
if ($ConnectTask.IsFaulted) {
$ConnectTask.Exception.InnerException.Message
$ConnectTask.Exception.InnerException.InnerException.Message
}
Once the ClientWebSocket
object is connected, I try this code to send a message.
$Source = [System.Threading.CancellationTokenSource]::new()
$Data = [System.Text.Encoding]::UTF8.GetBytes('Hello my name is Trevor Sullivan')
$ArraySegment = [System.ArraySegment[Byte]]::new($Data, 0, $Data.Length)
$SendTask = $WebSocket.SendAsync($ArraySegment, 'Text', $true, $Source.Token)
$SendTask.Wait()
$SendTask
The TaskResult
object shows a successful run to completion, but the message never appears on the server.
Id IsCompleted Status
-- ----------- ------
1 True RanToCompletion
The server is receiving the PowerShell keep-alive messages every 5 seconds, but it is not getting the message I'm explicitly sending. What can I do to fix this?
NOTE: I tested the exact same scenario with JavaScript (Node.js), using the ws
module, and it works perfectly fine. The server receives the message and logs it to the console.
Integrating Apache Kafka with millions of Internet facing devices is challenging. Typically used to interconnect backend systems, Kafka needs to delegate its messaging over the Internet to another service. WebSockets is the modern standard for implementing realtime messaging over the Internet. In this article, we discuss how to scale a WebSockets service to extend Kafka messaging to and from millions of connected devices. We also show how an Application Delivery Controller (ADC), such as F5 BIG-IP or Citrix ADC, can be used to accelerate Kafka messaging across the Internet.
When targeting users with iOS 13 or newer, recent websocket libraries from Apple, like https://developer.apple.com/documentation/foundation/urlsessionwebsockettask. I was wondering: isβ there any reason still to use Starscream over the new library? Can UrlSessionWebsocketTask automatic reconnect?
Hi!
I'm about to start a project that requires some web stuff but I also need websockets. I've used Rocket in the past and I'm pretty happy with it. I've found a few ways to do that like spawning a thread before I do rocket stuff where I do websockets with another library. But I think even that approach was from 2017 or whatever. Apart from that, I've found a bunch of discussions about how it will eventually work in Rocket but none of those are implemented.
So, in 2022, how do I get websockets into Rocket without switching frameworks to something that is a lot less comfortable for development?
is it bad to call api every 5-10 seconds per user or should i go full websocket?
Hello,
It seems the mqtt option of zwavejs2mqtt may not live a long life source
Does anyone have experience in migrating mqtt to websocket?
I would imagine the following steps should be executed:
config/.storage/core.device_registry
and config/.storage/core.entity_registry
)Thanks in advance.
edit: typo
edit2: updated after executing it
Hello, i made a chat server thay sucks a lot. Im posting this to encourge beginners like me :)
This is only the second time i attempt to write a server and im not very good at rusts idiomatics or know much about server theory [ :( ].
So, anyway, i learned about actix 2 days ago and tried to learn how it works, kinda failed cause theres like 2 tutorials on the internet...
The server runs on my pc and is reachable by other devices in my LAN, i was able to use it on pc: chrome and edge android: only opera
What it does: serves an index.html to log in only asking for a username, you cant get a username thats already taken. Then serves the chat page, is a lobby kinda chat, someone sends a message and everyone gets it. No storage of messages, no passwords.
I think the websockets are not supported 100% on chrome for android or maybe i should have used wss.
Made this cause im learning a little about web programming at school and i wanted to try something a little bigger in Rust.
And im posting cause when i tried to look for similar projects to use as a guide i couldnt find much.
Theres a gif of the server being used in the readme of the repo. Ignore my css, i was focusing on client javascript and the server.
I have a page with a ModelForm creating a game and just below a list of the games in progress. When I submit the form, I would like to dynamically refresh the list for all connected users. I use django channels. I use a jquery 'hack' to send a signal over a websocket prior to submit the form to tell the channel group about this new model instance in the dB. Then, the data is received by my consumer (receive function) and the receive function should use a message handler defined in the consumer.py file. The main issue is that the websocket is disconnected between the receive function processing and the message handler processing. Don't know if I am clear enough π I am stuck now, how would you proceed?
I'm using Socket IO Client and I'm connecting to the websocket server just fine. My only issue is when the events are received on the React app, the console logs the data argument multiple times, and I have no clue why. I even added a cleanup function to close the connection as well.
useEffect(() => {
console.log('Websocket useEffect');
const socket = io('http://localhost:3001');
socket.on('guildBanAdd', (data) => {
console.log(data);
});
socket.on('guildBanRemove', (data) => {
console.log(data);
});
return () => {
console.log('Close Websocket Connection');
socket.close();
};
}, []);
What I am trying to do is perform some state update that will need to call an API, but if the callback functions are being called more than once, wouldn't that be problematic?
One thing I noticed is, although it logs multiple times, if I actually call a function, like this
useEffect(() => {
console.log('Websocket useEffect');
const socket = io('http://localhost:3001');
socket.on('guildBanAdd', (data) => {
console.log(data);
someFunctionCall();
});
socket.on('guildBanRemove', (data) => {
console.log(data);
someOtherFunctionCall();
});
return () => {
console.log('Close Websocket Connection');
socket.close();
};
}, []);
It actually only calls that function once. Am I missing something specific to React here? If so, please explain. Thanks!
Hey boys and girls.
I'm working on a small e-commerce project and I'm looking for ideas to use websockets in an e-commerce environment. I want to use GraphQL subscriptions.
Thank you
Hi guys! I've tried my best to a chat. This project uses Nest.js, TypeORM, PostgreSQL, Passportjs/JWT, Socket.io. I'm quite new to Websockets, so not sure if I did it correctly. Will be glad to hear any feedback. Thanks!
Hi everybody, I'm trying to install laravel-websockets package but I'm getting the following error:
C:\xampp\htdocs\AdoptaUnaTiaBE>composer require beyondcode/laravel-websockets
Warning from https://repo.packagist.org: Support for Composer 1 is deprecated and some packages will not be available. You should upgrade to Composer 2. See https://blog.packagist.com/deprecating-composer-1-support/
Using version ^1.12 for beyondcode/laravel-websockets
./composer.json has been updated
Loading composer repositories with package information
Warning from https://repo.packagist.org: Support for Composer 1 is deprecated and some packages will not be available. You should upgrade to Composer 2. See https://blog.packagist.com/deprecating-composer-1-support/
Updating dependencies (including require-dev)
Your requirements could not be resolved to an installable set of packages.
Problem 1
- Installation request for pusher/pusher-php-server 7.0.1 -> satisfiable by pusher/pusher-php-server[7.0.1].
- beyondcode/laravel-websockets 1.12.0 requires pusher/pusher-php-server ^3.0|^4.0|^5.0 -> satisfiable by pusher/pusher-php-server[5.0.x-dev].
- beyondcode/laravel-websockets 1.x-dev requires pusher/pusher-php-server ^3.0|^4.0|^5.0 -> satisfiable by pusher/pusher-php-server[5.0.x-dev].
- Conclusion: don't install pusher/pusher-php-server 5.0.x-dev
- Installation request for beyondcode/laravel-websockets ^1.12 -> satisfiable by beyondcode/laravel-websockets[1.12.0, 1.x-dev].
Installation failed, reverting ./composer.json to its original content.
I tried changing composer.json to
"pusher/pusher-php-server": "7.0.1",
and using
composer update pusher/pusher-php-server
It didn't work, I also trtied directly yo do:
composer require pusher/pusher-php-server 7.0.1
but no solution, what can I do?
This os part of my composer.json file:
"require": {
"php": "^7.3",
"beyondcode/laravel-websockets": "^1.12",
"christiankuri/laravel-favorite": "^1.4",
"fabpot/goutte": "^4.0",
"fideloper/proxy": "^4.2",
"fruitcake/laravel-cors": "^2.0",
"guzzlehttp/guzzle": "7.4.x-dev",
"laravel-notification-channels/fcm": "~2.0",
"laravel/framework": "^8.0",
"laravel/passport": "^10.0",
"laravel/sanctum": "^2.6",
"laravel/tinker": "^2.0",
"maatwebsite/excel": "^3.1",
"mailgun/mailgun-php": "^3.0",
"pusher/pusher-
... keep reading on reddit β‘I'm building a browser script that uses both WebSocket and Three.
I'm serving the page that uses the script from node. The html in my page has the following to call my script:
<script type="module" src="myscript.js"></script>
With WebSocket I can:
$npm install websocket
...
const socket = new WebSocket();
I also install three with npm:
$npm install three
However, with Three, I need to import it with
import * as THREE from "three";
And when I do, Firefox gives me an error:
Uncaught TypeError: Error resolving module specifier βthreeβ. Relative module specifiers must start with β./β, β../β or β/β.
Thanks
Hi All -
I installed the docker image using portainer/stacks which for the most part went well (it helps if you set all the passwords).
Photoprism came up and was looking good until I tried to upload the first pictures. I got the "are you online" error message. Looking down the left-hand-side, I saw the OFFLINE indication and got to the description of how to set up reverse-proxies & websockets.
Being a noob at Docker and having never actually set up a reverse-proxy, I started looking for help in all the "normal" places. A couple of times I found references to a toggle-switch that disabled(?) websockets, but I have no idea where that might be.
Can someone provide a brief walk-through on how to get this thing online?
Is there a lightweight client for BTC with a possibility to get informed when the balance changes?
I've been working on a side project and I would love to hear people's opinion about it - any criticism is greatly appreciated: https://github.com/andersfylling/discordgateway
The discord gateway is typically used by discord bots to gain awareness of Discord state changes, such as new messages, members joining, commands called, etc.
The package provides a basic Discord shard implementation, along with tools to write your own shard. The idea is to split Discord behavior from low level websocket code, by treating the websocket connection as a pipe argument for different functionality.
The GatewayState, where the Discord behavior is defined, is designed to be "immutable"; once a pipe is closed or an error occurs, the internal state is destroyed and rendered unusable. You can then decide how to proceed based on the generic, or specialized, errors. DiscordError which holds close and operation codes received from Discord, and WebsocketError which wraps general websocket errors.
Here's a simple shard:
shard, err := gatewayshard.NewShard(0, os.Getenv("DISCORD_TOKEN"), nil,
discordgateway.WithGuildEvents(event.All()...),
discordgateway.WithDirectMessageEvents(intent.Events(intent.DirectMessageReactions)),
discordgateway.WithIdentifyConnectionProperties(&discordgateway.IdentifyConnectionProperties{
OS: runtime.GOOS,
Browser: "github.com/andersfylling/discordgateway v0",
Device: "tester",
}),
)
if err != nil {
log.Fatal(err)
}
reconnectStage:
dialUrl := "wss://gateway.discord.gg/?v=9&encoding=json"
if _, err := shard.Dial(context.Background(), dialUrl); err != nil {
log.Fatal("failed to open websocket connection. ", err)
}
if err = shard.EventLoop(context.Background()); err != nil {
reconnect := true
var discordErr *discordgateway.DiscordError
if errors.As(err, &discordErr) {
reconnect = discordErr.CanReconnect()
}
if reconnect {
logger.Infof("reconnecting: %s", discordErr.Error())
if err := shard.PrepareForReconnect(); err != nil {
logger.Fatal("failed to prepare for reconnect:", err)
}
goto reconnectStage
}
}
I have a weather station built with a raspberry pi that uses a websocket to publish its data. Is there any way I can query the websocket with Shortcuts? I am aware I could make some sort of RESTful API solution and use the "Get contents of URL" block, although I'd prefer to stick with the solution I have at the moment
Hello guys, I've been developing an online text game in Python using Quart and websockets. At the moment I'm trying to implement the multiplayer part but I'm having trouble handling multiple client input.
import asyncio
import janus
from functools import wraps
from quart import Quart, websocket
app = Quart(__name__)
connected_websockets = set()
def collect_websocket_with_queue(func):
@wraps(func)
async def wrapper(*args, **kwargs):
global connected_websockets
# queue = asyncio.Queue()
queue = janus.Queue().async_q
connected_websockets.add(queue)
try:
return await func(queue, *args, **kwargs)
finally:
connected_websockets.remove(queue)
return wrapper
user_input = []
@app.websocket('/queue')
@collect_websocket_with_queue
async def wsqueue(queue):
await websocket.send("Welcome")
await handlerQueue()
while True:
await websocket.send(await queue.get())
async def handlerQueue():
input_task = None
output_task = None
if len(connected_websockets) > 1:
output_task = asyncio.create_task(broadcast())
if output_task.done():
input_task = asyncio.create_task(getInput2())
async def broadcast():
for queue in connected_websockets:
await queue.put("What do you do [a] [b] or [c]")
async def getInput():
while len(user_input) < 2:
user_input.append(await websocket.receive())
async def getInput2():
user_input.append(await websocket.receive())
if __name__ == "__main__":
app.run(host="0.0.0.0", port=5000, debug=False)
At this point I can't find a way to make the program wait for both websocket connections to send their input. How could I make it wait for more than one websocket input? The flow I want is pretty much this:
Does anyone got a suggestion? I'm wondering generally, what would be the best way to implement a websocket endpoint which can handle multiple client input and output? Is there a framework that offers such functionality or could be a better alternative? Thanks for your time!
PS: I don't know whether I
... keep reading on reddit β‘Hello folks. My code connects to Twitter via V2 API and streams Tweets into a DB. I can only stream 2m Tweets per month and I'd like my code to be always running and streaming for the whole month, which means I can only ingest 1 tweet every 1.3 seconds (approximately). In my code I sleep for 1.3 seconds between each ingest, but this has the effect of keeping all my tweets way in the past. I'm only moving forward in the tweet stream 1.3 seconds at a time. I've been streaming for hours but my timestamps are hours behind. Is there a way to stream current tweets while still slowing things down?
response = requests.request("GET", url, headers=headers, stream=True)
tweets = 0
for response_line in response.iter_lines():
if response_line:
json_response = json.loads(response_line)
if json_response['data']['lang'] == 'en':
if push_to_loki(json_response):
time.sleep(1.3)
tweets += 1
if tweets % 10 == 0:
print(f"Ingested {tweets} tweets")
Stopped playing at 4am today, been fine for years. Woke up today and now Windows 7 is not supported because of the new Queue system? What is going on?
Initially I went the ignorant way by implementing a completely custom global state system. I learned a ton, but things start to crumble. Now I want to switch to React Redux Toolkit. I'm looking for feedback on my proposed approach.
Previously I treated 99% of the data in the store as cache. At app start-up all stored/cached data would be loaded locally to the store and a websocket would be opened to check for and constantly receive updates. Never would the client make a direct update to the store. It would request an update (say REQUEST_CHANGE_NAME) over the socket. If an update message was received from the back-end, the store would be updated accordingly (say UPDATE_NAME). I like this approach, because it explicitly makes the back-end the single source of truth, it is consistent and makes the infra easier to scale. Also, a lot of the app user's state is updated by other app users and therefore pushed autonomously by the back-end to the client. What do you think of the approach?
I'm (still) researching on how to copy such an approach with RTK (Query). But, the info I found always suggest to open a socket connection for one specific slice, while before I basically made one socket connection to update all "slices" in my custom store implementation. Any ideas? How would you tackle such a thing?
And also, happy holidays ;)
I am using gorilla for websockets.
This is how I setup my Mux.
c := cors.New(cors.Options{
AllowedOrigins: allowedOrigins,
AllowCredentials: true,
Debug: false,
})
This is my upgrader
var upgrader = websocket.Upgrader{
ReadBufferSize: 1024,
WriteBufferSize: 1024,
CheckOrigin: func(r *http.Request) bool {
for _, allowedOrigin := range allowedOrigins {
if allowedOrigin == r.Header["Origin"][0] {
return true
}
}
return false
},
}
My `/ws` route is setup normally like other handlers.
Now CheckOrigin is failing my testcases because of panics but Its working fine if I remove check origin from upgrader.
Do I really need to double check origin for my websocket handler?
So I need help with a web socket, I'm making a poker online for a personal project, and the problem I'm having is that I don't know how to stream the data to the room.
I have done the handler of the room creator and room joiner, and I use MongoDB. Any help would mean the world to me, because I've been trying to do this for like 2 weeks and at this point I'm burned out.
Hello everybody, I'm trying to use laravel-websockets wich implements pusher server but for some reason I can't listen to events even though I can see the events in laravel websockets dashboard and in console.
https://github.com/beyondcode/laravel-websockets
In client( I'm using ngrok since I'm testing on local machine):
This is how I setup Pusher client and echo, I'm not receiving any alert:
//BASE_URL = https://9fa8-88-5-254-23.ngrok.io
const startPusherChatServerBetter = () =>
{
Pusher.logToConsole = true;
let options = {
key: env.PUSHER_APP_KEY,
wsHost: env.BASE_URL,
wsPort: '6001',
wssPort: '6001',
disableStats: true,
logToConsole: true,
encrypted: false,
enabledTransports: ['wss','ws'],
};
let PusherClient = new Pusher(options.key, options);
PusherClient.connection.bind( 'error', () => console.log('PusherClient::error', arguments))
const echo = new Echo({
broadcaster: 'pusher',
client: PusherClient,
...options
});
echo.channel('chat').listen('MessageSent', (e) => {
Alert.alert('RECEIVED');
})
.listenForWhisper('typing', (user) => {
console.log('An user is typing...');
});
};
In backend:
How I fire event:
broadcast(new MessageSent($message));
My event:
<?php
namespace App\Events;
use Illuminate\Broadcasting\Channel;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Broadcasting\PresenceChannel;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use Illuminate\Contracts\Broadcasting\ShouldBroadcastNow;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;
use App\Models\User;
use App\Models\Message;
class MessageSent implements ShouldBroadcastNow
{
use Dispatchable, InteractsWithSockets, SerializesModels;
public $message;
/**
* Create a new event instance.
*
* @return void
*/
public function __construct(Message $message)
{
$this->message = $message;
}
/**
* Get the channels the event should broadcast on.
*
* @return \Illuminate\Broadcasting\Channel|array
*/
public function broadcastOn()
{
return new Channel('chat');
}
}
Channels file:
... keep reading on reddit β‘Please note that this site uses cookies to personalise content and adverts, to provide social media features, and to analyse web traffic. Click here for more information.