How can I notify a client of a request initiated by another client with websocket? - websocket

I'm new to software development in general, and I'm writing a backend for a simple ride-sharing iOS application (which I'll develop later). I'm using Vapor to create the backend.
When a user makes a trip request to the API, I want to create a new trip and establish a websocket session between the user and a driver. The problem I'm having is how can I notify a driver that a request is in and add him to the session?
Here's what I've come up with so far, although I'm not sure if it's going to work:
When a trip request comes in, I would create a session and a trip object with the session id. When a driver visits the "Trip requests" tab in the app he would make a get request to retrieve active trip requests. When he then clicks on one of the trip requests, he would make a request with the session id of that particular trip to be added to that session.
The problems I'm seeing with the above solution is that that would make the User the Poster, and the Driver the Observer, which I'm not sure is the way to go since I want the driver to act as a poster (to send location updates so that the user can track the driver on the map in real time).
Another problem is that users would have to wait indefinitely before a driver accepts their request.
Is there a better way to notify the driver of a trip request? How can I go about achieving this?

First, you will get trouble when trying to establish a direct connection between user and driver, because it's quite difficult to directly connect to an app on a smartphone (changing IPs, NAT, firewalls and opening ports are some of the problems).
I'd suggest, you implement some kind of REST API for the trips/trip requests. To notify the driver or send updates back to the user, you can either use push notifications (for iOS it's APNS) or websockets. In the best case both for different situations.
Here are some hints for further research on those topics:
WebSockets: In Vapor, an example chat app using websockets , WebSocket wrapper for Vapor
Push notifications: Gorush, push notification server, Apple Notifications, (WIP: APNS on NIO)
I hope that helps for your next steps. Your question is quite broad to be more specific.

Related

Should socket.io server update the database?

I’m bulilding a web app that requires communication between clients. For this I’m using socket.io. Some data however has to be updated regularly in the database.
Some of them not that often (preferences, on button click) others in every second for example a timer value. This can not be calculated because the timer can be paused.
Right now whenever a client emits an event, it also makes a request to the backend to updated the database. I was wondering if it would be a good idea to have the socket.io server update the database so the clients would only have to take care of the socket communication? It seems to me that having the browser do a request to the backend is a bit resource heavy and takes out a bit from the advantages of the socket based communication
Edit: the back end of the app and the socket server are two different servers but physically they are on the same machine so their communication could be faster
the main point of using socket.io is that it allows you to push data to clients and clients do not need to check your server constantly to get the last changes, and providing a low-overhead communication channel between the server and the client.
you can call an API and also emit data and many other things on user click in your application.
it is a good idea to have the socket.io server update the database and you can also authorize each socket, save client sockets information and ...

Can we replicate a HTTP SESSION idea in a MQTT architecture?

Roughly speaking a HTTP SESSION is a kind of secret that the server sends to the client (ex browser) after user's credentials is checked. This secret is passed trough all subsequents HTTP requests and will identify the user. This is important because HTTP are stateless - source.
Now I have a scenario where there is a communication between a machine and a MQTT broker inside the AWS-IoT core. The machine displays some screens. The first screen is the login and password.
The idea here is that after the first screen, IF the credentials are validated, the server should generate a "session" and we should send this "session" across the screen pages. The machine should send this "SESSION" in all subsequent messages and the server must to validate this string before any action. This is a request created by an electrical engineering team.
Me, in the software development side it seems that make no sense since all machines to be connected in the AWS IoT-Core broker (MQTT) must to use a certificate - with is the validation already.
Beside of that, the MQTT broker offers the SESSION persistence capabilities. I know that the SESSIONs (QoS 0/1) in the broker side are related to idea of confidence of delivery and reception of a message.
That being said is it possible to use session persistence in MQTT to behavior like a sessions in HTTP in order to identify users across screens in devices? If yes how?
No, HTTP Session concept is not in any way similar to the MQTT session. The only thing held in a MQTT clients session is the list of subscribed topics, a HTTP session can hold arbitrary data.
Also MQTT messages hold NO information about the user or even the client that published the message when it is delivered to the subscriber, the ONLY information present is the message payload and the topic it was published to.
While MQTTv5 adds the option to include more metadata, trying to add the concept of users sessions is like trying to make a square peg fit in round hole.
If you want to implement something as part of the message payload then that is entirely up to you, but it is nothing to do with the transport protocol.

Reflect one client's message to another client on Websocket (golang)

I'm having a problem using websockets in my backend. I have to re-write some old with golang and old developer using websocket while one client tracking other client's location.
both client connecting websocket with given url
"\(URLConstants.webSocketURL)?token=\(token)&jobId=\(jobId)"
So I thought both client connecting websocket with her/his own token and I need to reflect user's message to other user. I can open two sockets with given url.
It's the first time that I'm using websocket so I'm not sure I'm asking the right question.
You need to send the information to the existing sessions that you stored from opened connection and distribute the information to other users.
Try to go through this solution to get some inspiration https://github.com/suricatatalk/core/blob/master/core.go.

The theory of websockets with API

I have an API running on a server, which handle users connection and a messaging system.
Beside that, I launched a websocket on that same server, waiting for connections and stuff.
And let's say we can get access to this by an Android app.
I'm having troubles to figure out what I should do now, here are my thoughts:
1 - When a user connect to the app, the API connect to the websocket. We allow the Android app only to listen on this socket to get new messages. When the user want to answer, the Android app send a message to the API. The API writes itself the received message to the socket, which will be read back by the Android app used by another user.
This way, the API can store the message in database before writing it in the socket.
2- The API does not connect to the websocket in any way. The Android app listen and write to the websocket when needed, and should, when writing to the websocket, also send a request to the API so it can store the message in DB.
May be none of the above is correct, please let me know
EDIT
I already understood why I should use a websocket, seems like it's the best way to have this "real time" system (when getting a new message for example) instead of forcing the client to make an HTTP request every x seconds to check if there are new messages.
What I still don't understand, is how it is suppose to communicate with my database. Sorry if my example is not clear, but I'll try to keep going with it :
My messaging system need to store all messages in my API database, to have some kind of historic of the conversation.
But it seems like a websocket must be running separately from the API, I mean it's another program right? Because it's not for HTTP requests
So should the API also listen to this websocket to catch new messages and store them?
You really have not described what the requirements are for your application so it's hard for us to directly advise what your app should do. You really shouldn't start out your analysis by saying that you have a webSocket and you're trying to figure out what to do with it. Instead, lay out the requirements of your app and figure out what technology will best meet those requirements.
Since your requirements are not clear, I'll talk about what a webSocket is best used for and what more traditional http requests are best used for.
Here are some characteristics of a webSocket:
It's designed to be continuously connected over some longer duration of time (much longer than the duration of one exchange between client and server).
The connection is typically made from a client to a server.
Once the connection is established, then data can be sent in either direction from client to server or from server to client at any time. This is a huge difference from a typical http request where data can only be requested by the client - with an http request the server can not initiate the sending of data to the client.
A webSocket is not a request/response architecture by default. In fact to make it work like request/response requires building a layer on top of the webSocket protocol so you can tell which response goes with which request. http is natively request/response.
Because a webSocket is designed to be continuously connected (or at least connected for some duration of time), it works very well (and with lower overhead) for situations where there is frequent communication between the two endpoints. The connection is already established and data can just be sent without any connection establishment overhead. In addition, the overhead per message is typically smaller with a webSocket than with http.
So, here are a couple typical reasons why you might choose one over the other.
If you need to be able to send data from server to client without having the client regular poll for new data, then a webSocket is very well designed for that and http cannot do that.
If you are frequently sending lots of small bits of data (for example, a temperature probe sending the current temperature every 10 seconds), then a webSocket will incur less network and server overhead than initiating a new http request for every new piece of data.
If you don't have either of the above situations, then you may not have any real need for a webSocket and an http request/response model may just be simpler.
If you really need request/response where a specific response is tied to a specific request, then that is built into http and is not a built-in feature of webSockets.
You may also find these other posts useful:
What are the pitfalls of using Websockets in place of RESTful HTTP?
What's the difference between WebSocket and plain socket communication?
Push notification | is websocket mandatory?
How does WebSockets server architecture work?
Response to Your Edit
But it seems like a websocket must be running separately from the API,
I mean it's another program right? Because it's not for HTTP requests
The same process that supports your API can also be serving the webSocket connections. Thus, when you get incoming data on the webSocket, you can just write it directly to the database the same way the API would access the database. So, NO the webSocket server does not have to be a separate program or process.
So should the API also listen to this websocket to catch new messages
and store them?
No, I don't think so. Only one process can be listening to a set of incoming webSocket connections.

Websockets or AJAX or both?

I am a bit confused about how one uses websockets. I have already set up a websocket server and are able to receive from server and send to server.
My question is. When using websockets, are you supposed to drop the ajax part completely? Or are you supposed to use websockets alongside ajax?
Example:
I want to use websockets on a chat service on a website where users can log in. When logging in, I use ajax. When on the message page I use websockets to receive future messages, and send future messages. But when navigating to the messages page, I use ajax to get the messages from database.
Is this the correct way of using websockets? Or should I do everything in websockets since 1 user 1 active connection is more efficient? Or should 1 user have 1 websocket connection, but still keep sending ajax requests to the server when navigating to some pages without reloading the site, using ajax?
What is the best practice when creating a large application where users can log in, navigate to pages to load stuff async, but still wanting that bidirectional real time benefits of websockets on stuff like messaging services and notification services on that same website?
There is no reason you cannot use both. I think the solution depends on what server side resources you are using. I may need access to a server through websockets to get updates to a chat dialogue. I may use a completely different system to get user statistics or provide authentication.
I don't think there is a specific answer to your question as it varies depending on the application in question.

Resources