Connect Laravel echo from Angular project - websocket

I have a Laravel-echo-server with Redis running on my local.
I created a test API endpoint, that emits broadcastable event.
on http://localhost:8000/api/web-socket-test I see the response in echo server CLI.
I set-up laravel-echo auth key and I can get the stat info from server API
http://localhost:6001/apps/APP_ID/status?auth_key=b73a61d0.
The problem is with connecting to echo-server from Angular via ws: protocol.
My connection code is
import {webSocket, WebSocketSubject} from 'rxjs/webSocket';
export class MyComponent implements OnInit, OnDestroy {
myWebSocket: WebSocketSubject<any> = webSocket('ws://127.0.0.1:6001');
ngOnInit() {
this.myWebSocket.subscribe(
msg => console.log('message received: ' + msg),
err => console.log(err),
() => console.log('complete')
);
}
And finally I've got an error: WebSocket connection to 'ws://127.0.0.1:6001/' failed: Connection closed before receiving a handshake response.
How can I establish ws connection?

I believe you want to try connecting using the socket.io client libraries instead of using rxjs raw websockets.
Although it's not immediately clear from the laravel echo server docs, the project title states it's a 'Socket.io server for Laravel Echo'. So I'm assuming you should use the socket.io client libraries for connections.

Related

Laravel listen socket.io client emit

I have chat application using Laravel + laravel-echo-server + Redis.
currently i am using http api request from client to send message.
But its slow if i have large client number.
Is there a way to send message from client to server through socket and listen in laravel?
Probably something like this
public function onMessage($client, $data)
{
.....
}
i already tried laravel-websocket, but if i set APP_DEBUG=false in .env CustomSocketHandler unable to work anymore.
Thank you.

How to establish web socket on server side for chat implementation?

If i don't have server details then who will establish or install the web socket connection? Can admin (who handle our host) establish connection and provide me the URL of websocket to use in android or angular code?
Is this necessary to write code in php?
I expect server admin install and configure web socket and provide to use in chat module.
Web admin(Ops) can help create the domain name but you have to write serverside code to handle websocket connection. You can use any programming language that supports websocket. for example,
nodejs - https://github.com/websockets/ws
java - https://docs.oracle.com/javaee/7/api/javax/websocket/package-summary.html
With java websocket you simply can define ServerEndpoint and deploy the war(web archive) to any host or cloud provider(Amazon cloud, google cloud etc),
#ServerEndpoint("/chat/{clientId}")
public class MyWebsocketServer {
#OnMessage
public String handleMessage(#PathParam("clientId") String clientId,
String message,
Session session) {
System.out.println("chat message: " + clientId + "/" +message);
return "hi how are you doing?";
}
}
Now, with javascript as a client your code to establish WebSocket connection would be:
var clientId = Math.random().toString(36).substring(2) + (new Date()).getTime().toString(36);
var webSocket = new WebSocket("ws://localhost:8080/my-app/chat/" + clientId);
localhost means I'm running both Server and Client in same host, in your case serving host might be www.mike-simons.com/chat while client running on phone
Example: https://github.com/duwamish-os/chat-server_websocket-java

How to troubleshoot Laravel Broadcasts + Pusher..?

I'm following the Laravel Documentation to set up broadcasting using Pusher, and it looks pretty straight-forward, but I haven't gotten it work yet, so I must have made a mistake somewhere along the way.
Here's what I've done:
Server Side
I've created an Event that implements the ShouldBroadcastNow interface and defined the broadcastsOn() method.
class ThreadMessageCreated implements ShouldBroadcastNow {
use Dispatchable, InteractsWithSockets, SerializesModels;
public function broadcastOn() {
return new Channel('bobtest');
}
I'm raising the Event from one of my API Controllers:
public function createMessage(Thread $thread, Request $request) {
...
event(new ThreadMessageCreated($message, $thread));
return $message;
}
I've configured my pusher credentials in my .env file.
Client Side
I've configured Laravel Echo on the Client side (via the angular-laravel-echo package) and subscribed my client to the channel.
ngOnInit() {
this.echo
.join('bobtest', 'public')
.listen('bobtest', 'ThreadMessageCreated')
.subscribe(()=>alert('message received'));
console.log(this.echo);
}
However, when my API endpoint is hit, the event is fired, but I don't see anything on the client side.
So, I added logging in the broadcastOn() method to verify it's getting called. Then I changed the driver from pusher to log and I do see the Broadcast info getting written to the laravel.log file.
So, I'm assuming that the broadcast is also happening when using the Pusher driver, and either isn't being sent out from Laravel, or isn't being received by the Client.
I'm new to sockets, pusher, & Laravel Echo, so I'm not sure where to look for more info to track this down.
I don't see any errors in the laravel.log file.
I don't see any errors in Chrome Dev Tools on the client side.
I logged into pusher and there are no errors in the 'Error Logs' tab
What can I do to get more details to figure out where the problem is occurring?
Thanks! :-)
[UPDATE]
I can see the broadcasts are appearing in my pusher account, so the problem seems to be on the client side. Perhaps I'm not subscribing correctly to the right channel?
Also, I'm using Laravel as the back end only, using JWT Authentication. I'm currently not using the laravel csrf token, not sure if that could pertinent or not.
I now learned I can see web socket data in Dev Tools. I'm assuming this error was there before, I just didn't notice it. I guess the 101 status code didn't stand out to me :-o
But after looking in Dev Tools, I could clearly see this error:
{
message: "App key xxx not in this cluster. Did you forget to specify the cluster?",
event: "pusher:error"
}
To view Web Socket activity:
Dev Tools > Network > Filter > WS (Web Sockets):
In my case, I simply needed to specify the cluster in the Laravel Echo config:
window.Echo = new Echo({
broadcaster: 'pusher',
key: 'xxxxxxxxxxxxxxxxxxxx',
cluster: 'us2', <--------------[pusher needs a cluster :-)]
host: 'http://the-host.com',
auth: {
headers: {
'Authorization': 'Bearer ' + token
}
}
});

socket.io to talk to server that is implementing RFC6455 in a strict fashion

I am trying to make my socket.io javascript client talk to a server implemented in cpp using websocketpp and its not working. Its surprising that I cant configure socket.io to fall back to real websockets when I need them.
Any one has any ideas or suggestions on this ? going back to websocket npm and re implementing my client is the only way ?
I tried this, but it does not work
var socket = io.connect('http://localhost:8080', {
transports: [
'websocket',
'polling'
]
});
socket.io is an additional protocol on top of webSocket so a socket.io client can ONLY talk to a socket.io server. While socket.io uses webSocket for the transport, it needs support for it's additional layer on top of webSocket to work properly.
If you want to talk to a plain webSocket server, then you should use a plain webSocket client.
var socket = new WebSocket('ws://localhost:8080');
// Connection opened
socket.addEventListener('open', function (event) {
socket.send('Hello Server!');
});
// Listen for messages
socket.addEventListener('message', function (event) {
console.log('Message from server', event.data);
});
You can probably find a socket.io server modules for cpp if you'd like to fix the server-side of things to talk socket.io.

How to configure my sails app with https socket connection?

I have a sails backend API. And I already have an https connection.
(https://myapp.com/api)
How do I connect to a sails socket with my client side (Android and iOS) having an https connection? I dont have any problem connecting to a non HTTPS server. Hope there is a help.
all you have to do is open config/bootstrap.js, and made following changes there
module.exports.bootstrap = function(cb) {
// handle connect socket first event executes after logged in
sails.io.on('connect', function (socket){
socket.emit("connected",{ data: "here am i!" })
});
// handle custom listener for other stuff
sails.io.on('ping', function (socket){
socket.emit("pong",{ data: "send to android/ios/web client" })
});
cb();
};
here you can listen for multiple events as well as you can emit multiple private/broadcast messages as well and also all socket.io listeners will work here

Resources