How to use socket.io in RestApplication of loopback 4? - websocket

I have created my rest application in Loopback 4 and now I want to implement socket in it. Is there any way to do so in RestApplication?
export class MyApplication extends BootMixin(
ServiceMixin(RepositoryMixin(RestApplication)),
) {
constructor(
options: ApplicationConfig = {}
) {
super(options);
}
....
async start() {
await super.start();
const io = socketio(this.restServer);
io.on('connection', (socket: any) => {
console.log('connected');
});
}
}
const io = socketio(this.restServer); isn't working for me

Here is a Official Loopback 4 example with socket.io integration. This example is created to explore how to expose Websocket (socket.io) endpoints in conjunction with LoopBack controllers.
https://github.com/raymondfeng/loopback4-example-websocket

I have created my rest application in Loopback 4 and now I want to implement socket in it.
What is your demand? After Customer A successfully calls a REST API, and the result of this call will be sent to the specified client via websocket?
You can created both rest server and websocket server at the same time in application.ts (how to creat websocket server). Then you can create Interceptor to send message via websocket after each controller method is called.

Related

Masstransit: GetSendEndpoint

I have a producer, which send more than 1000 messages in a minute to a specific endpoint. I’m using Microsoft DI and I’ve configured the send Endpoint as described here https://masstransit-project.com/usage/producers.html#send .
// Masstransit setup
serviceCollection.AddMassTransit(mt =>
{
mt.UsingAzureServiceBus((ctx, cfg) =>
{
cfg.Host(massTransitSettings.TestServiceBusConnectionString);
cfg.ReceiveEndpoint("mytestmessage", e =>
{
e.MaxDeliveryCount = 3; //How many times the transport will redeliver the message on negative acknowledgment
});
});
});
serviceCollection.AddTransient<ITestMessageProducer, TestMessageProducer>();
// Producer setup
public class TestMessageProducer : ITestMessageProducer
{
private readonly ISendEndpointProvider _testEndpoint;
public TestMessageProducer(ISendEndpointProvider testEndpoint)
{
_testEndpoint = testEndpoint;
}
public async Task SendTestMessage(ITestMessage testmessage)
{
var endpoint = await _testEndpoint.GetSendEndpoint(new Uri("queue:mytestmessage"));
await endpoint.Send(testmessage);
}
}
Query:
The SendTestMessage function has been called very frequently as mention above. Will it be ok to call “GetSendEndpoint” everytime? I have read somewhere that GetSendEndpoint creates a new instance of ISendEndpoint everytime.
Will the MaxDeliveryCount still be worked on my sendendpoint?
Thank you.
Send endpoints are cached by address, only a single instance will be created.
MaxDeliveryCount is a receive endpoint concern, but you should not configure a receive endpoint without consumers as all messages will be moved to the _skipped queue.

Vert.x SockJSHandler class

I'm trying to build a web socket application with Vert.x, and I have found plenty of examples using the SockJSHandler, to communicate with SockJS javascript library on the front end of the application.
The examples are using version 3.5.0 of Vert.x Core and Vert.x Web, and they create an instance of the class using the method SockJSHandler.create(vertx), bridging the SockJSHandler to the Vert.x event bus through the method SockJSHandler.bridge. This last method returns the type SockJSHandler, that gets routed with router.route("/eventbusroute/*").handler(sockJsHandler()).
I'm using the latest version of Vert.x Core and Vert.x Web, the 3.8.3, and in this release the method bridge returns an instance of type Router, as stated in the documentation.
My question is: what would be the best way to route the SockJSHandler Router instance to a particular route?
see e.g.
https://vertx.io/docs/vertx-web/java/
Router router = Router.router(vertx);
SockJSHandler sockJSHandler = SockJSHandler.create(vertx);
BridgeOptions options = new BridgeOptions();
// mount the bridge on the router
router.mountSubRouter("/eventbus", sockJSHandler.bridge(options));
vertx/examples/service/ProcessorServiceVerticle.java
Router router = Router.router(vertx);
// Allow events for the designated addresses in/out of the event bus bridge
BridgeOptions opts = new BridgeOptions()
.addInboundPermitted(new PermittedOptions().setAddress("vertx.processor"))
.addOutboundPermitted(new PermittedOptions().setAddress("vertx.processor"));
// Create the event bus bridge and add it to the router.
router.mountSubRouter("/eventbus", SockJSHandler.create(vertx).bridge(opts));
router.route().handler(StaticHandler.create());
Code which works for me:
Router router = Router.router(vertx);
BridgeOptions options = new BridgeOptions();
options.addOutboundPermitted(new PermittedOptions().setAddressRegex(".*"));
options.addInboundPermitted(new PermittedOptions().setAddressRegex(".*"));
SockJSHandler sockJSHandler = SockJSHandler.create(vertx);
router.mountSubRouter("/eventbus", sockJSHandler.bridge(options));
I've found the documentation I needed in version 3.8.2 deprecations documentation.
The correct way to handle the SockJSHandler.bridge return value is to include it as a subrouter.
So, instead of using the SockJSHandler implementation like the (pre Vert.x web 3.8.2 version):
EventBus eventBus = vertx.eventBus();
Handler<BridgeEvent> handler = ...;
SockJSHandler sockJSHandler = SockJSHandler.create(vertx).bridge(options, handler);
Router router = Router.router(vertx);
router.route("/eventbusroute/*").handler(sockJSHandler);
One must include the result of the bridge method call as a subRouter like this (Vert.x web version 3.8.2+):
EventBus eventBus = vertx.eventBus();
Handler<BridgeEvent> handler = ...;
Router sockJSSubRouter = SockJSHandler.create(vertx).bridge(options, handler);
Router router = Router.router(vertx);
router.mountSubRouter("/eventbusroute", sockJSSubRouter);

Asp .Net Core Web API where to subscribe RabbitMQ

I am trying to implement publish/subscribe architecture using Web API and Rabbit MQ message broker.
I have two projects in my solution: Publisher and Subscriber.
Publishing is implementing successfully but I cannot find place in my
subscriber project to read published message from the queue.
Both of my projects are .Net Core ASP WEB API
Thanks in advance
Register rabbitMq as HostedService using the AddSingleton method in ConfigureServices Method. IHostedService internally calls ApplicationGetStarted event. So the rabbit starts listening there
public void ConfigureServices(IServiceCollection services)
{
services.AddMassTransit(x =>
{
x.UsingRabbitMq();
});
// OPTIONAL, but can be used to configure the bus options
services.AddOptions<MassTransitHostOptions>()
.Configure(options =>
{
// if specified, waits until the bus is started before
// returning from IHostedService.StartAsync
// default is false
options.WaitUntilStarted = true;
// if specified, limits the wait time when starting the bus
options.StartTimeout = TimeSpan.FromSeconds(10);
// if specified, limits the wait time when stopping the bus
options.StopTimeout = TimeSpan.FromSeconds(30);
});
}
}

What's the difference between socket.to(id) and socket.broadcast.to(id)?

I'm write an application using socket.io.
I'm confused by the official document about socket.broadcast.
From my testing, the below code has the same effect:
socket.to(id).emit('some event')
socket.broadcast.to(id).emit('some event')
What's does broadcast do?
broadcast sets a flag in socket,
Socket.prototype.__defineGetter__('broadcast', function () {
this.flags.broadcast = true;
return this;
});
which tells the manager to omit current socket from broadcasting
Socket.prototype.packet = function (packet) {
if (this.flags.broadcast) {
this.log.debug('broadcasting packet');
this.namespace.in(this.flags.room).except(this.id).packet(packet);
} else {
...
Thus socket.broadcast.to(room) will have the following effect: client that is connected to the socket will not receive the message. Whereas when socket.to(room) all room's clients will receive the message including the one who is connected to socket.
I've just verified this for socket v0.9 but I doubt these mechanics are different for v1.+

How do i know if i'm disconnected from a Dart websocket server

I created a WebSocket server, and it works just fine, however, i don't know how to detect if a client is disconnected, can anyone help me ?
here is my code:
import 'dart:io';
const port=8080;
List users=new List();
void main() {
HttpServer.bind('127.0.0.1', port)
.then((HttpServer server)=>
server.listen((HttpRequest request) =>
WebSocketTransformer.upgrade(request).then((WebSocket websocket) {
//what can i do here to detect if my websocket is closed
users.add(websocket);
websocket.add("clients Number is ${users.length}");
})
)
);
}
Since a WebSocket is a Stream it will close when the socket is disconnected. This is a nice property of many of the dart:io classes implementing Stream - you can interact with them al lthe same way, once you know how to use Streams.
You can detect when a Stream closes in several ways:
Add an onDone handler to your listen() call:
websocket.listen(handler, onDone: doneHandler);
Add an on-done handler to the StreamSubscription returned from listen():
var sub = websocket.listen(handler);
sub.onDone(doneHandler);
Turn the StreamSubscription into a Future via asFuture() and wait for it to complete:
var sub = websocket.listen(handler);
sub.asFuture().then((_) => doneHandler);

Resources