WEB SOCKET PHP concept - php

I want to keep a persist connection between my server and clients (android app) so I can push data from server to my clients. After some search I found that the best way to do is WEB SOCKET. But there is two scenarios in here:
first is, I need to sent some data (command) like broad cast to some of my clients (not all) and then listen for their reply. And second is, I need to sent a notify to some of clients.
It's like chat room that there is a general room that the messages can be seen by everybody in room and some private rooms that messages can be seen just by two users who participate in chat.
I saw some example code but I couldn't understand the different between those two scenarios in codes. I need also some information about ZeroMQ and does it worth to use ZeroMQ for the project or not?
Just some links of references would be appreciated.
EDIT
I saw in code that people define some infinite loop to check some event but my idea is to create a virtual client in server that can call by other function so I don't need to change anything in DB and then check for event in my loop. the event can call this virtual client that can sent my command in broad cast. is that a proper way to do that?

Use Ratchet for this, It is a PHP library providing developers with tools to create real time, bi-directional applications between clients and servers over WebSockets.
You can use it's subscribe/unsubscribe (Topics) feature, which will fulfill your needs to send push notification in general and to specific users. Create different topics for them.
e.g. One topic would be general for which every user will get registered on page load and one would be for specific users. You can create as many as topics you need.

Related

Refreshing chat messages in iOS chat app

I am currently creating an app where 2 users will have the ability to chat with one another. Specifically, it will be an iOS app using Swift as the main language. Most chat app tutorials on the web recommend using Firebase but I personally want to use MySQL since the rest of my database activities for this app are done using MySQL. I also do not want to use any existing libraries and want to do this all on my own.
I only have questions regarding the efficiency of using MySQL. When accessing the database, I create a URLSession using swift which then uses a predetermined link that points to my PHP scripts on the backend to handle the database accessions. The only problem with this is that my chat functionality of the app will have to refresh messages (to see messages that the other user has sent you within a second or so). I am confused as how to go about this. My current idea is to have a Timer that calls the URLSession data task every second or so to retrieve new messages from the database then display them on the user's screen. Would this be efficient or is there a better way to do this? I feel as if this would bog down MySQL in some way and would over all slow down the efficiency of the database. Is there a better way to go about this?
Thanks in advance.
If you really want to use MYSQL as a way of delivering messages then you can look into #TekShock's comment about using Apple's PushNotifications. You can also use Long Polling however it is not favorable at all.
I personally would not use MYSQL as a way of delivering messages just because there is a lot more better options. You can pick from messaging protocols like XMPP and MQTT to deliver your messages. I have personally have used MQTT in the past and thought it was really simple to get the hang and will fit your needs perfectly. It has a couple of really good swift clients like SwiftMQTT. You will have each device subscribe and publish to a room so it can receive and send messages. So in your case you can have a User A subscribe to ROOM 1 and a User B subscribe to the same room and they will both receive all the messages published to that specific room.
You can then if you want to store delivered messages to a MYSQL db so when the user opens the app back up you can load all their previous messages. You can also use Sqlite or Realm to store these messages locally instead of storing them online.
EDIT:
Scaling is also pretty simple with MQTT if this is something you will consider. You could place a queuing system between your application and the MQTT broker, possibly something like Apache Kafka which would be your best bet.

Best structure for developing a messaging server

I'm developing an app that will have a way to message other users. I've done this before but I think I can improve on the method of sending/receiving the data. Before what I did is I had a table with all the messages and the ones that were associated with the conversation ID would be displayed in an individual conversation. On the client side, I'd have a timer that would constantly ask the server for an update.
I guess my question is this: Is there a better way than to keep asking my server if there is an update? I mean.. a lighter way. I was considering using push notifications but if the user disables APNS, their messages won't update.
http://reactphp.org/
Is useful for event driven socket based communication. It would involve storing connected clients in some kind of data structure (see here) and on an event, such as a change to data, notifying connected clients that should know about the event, in the manner of a push.
http://socketo.me/ is built on top of react
http://socketo.me/docs/flow
has a good diagram of how socket based connections work. This might be better than polling repeatedly from all the connected clients, based on your use case.

Socket.io private message notification

Hey there stackoverflow!
I am developing a community with Laravel3 right now I am trying to achieve some Facebook style private messaging.
I did the coding part, but me and my friends are so agree about adding real-time message notifications. I did my research, I cannot say I find a good article about this, some of them starts with oh you know everything about matrix so lets socketsocketsocketsocketsocket I am so confused how to start, where to start, what is this anyway, many of this say go with MongoDB never use MySQL again. Dude what the heck? I am using MySQL I created a nice private message system in Laravel, I want to add real-time notify!
All I want to do is
UserA sends a message to UserB
Message inserted into privmsg table.
Sockets or whatever you suggest, tells UserB's browser there is +1 new message from UserA
UserB sees there is one unread message without refresh his page and click to read it .
How can I achieve this? Socket.io best choice for that? if so how can I use it? any snippets would be so great! or tutorial about my situation :)
I would really grateful
You suffer from the problem of thinking "X is always better than Y so just always use X". There's probably a name for it... maybe even a book or two written. Who knows. Let's start with your first question:
what is this shit anyway, many of this say "go with MongoDB never use MySQL again." Dude what the heck?
You should stop spending time with whomever said that. MySQL and MongoDB are database systems for two very different types of databases. They are often referred to as table-based and document-based. With MySQL (any many other databases that utilize SQL... and probably some that don't), your data is stored in a set of relational tables outlined by a very specific schema. Each record in this table conforms to a specific set of fields with a specific set of types. This type of database is perfect for many kinds of data.
MongoDB is the document-based variety of databases, commonly referred to as "NoSQL" (meaning not-only-SQL). Each "document" can have a whole structure, complete with nodes that have children and grand children. Each document can have its own distinct set of data. Documents are stored in "collections". This type of database has some advantages... it can be quite fast for certain types of operations. This being said, it is terrible for other things, such as when you have a bunch of data that is all identical in type. Data aggregation is very slow on databases like these (but it is getting better all the time!).
The point I'm trying to make is that MySQL and MongoDB are just different tools, designed for different jobs. Stop pounding a nail with your screwdriver just because your friend tells you that screws are better than nails.
All I want to do is: UserA sends a message to UserB; Message inserted into privmsg table.; Sockets or whatever you suggest, tells UserB's browser there is +1 new message from UserA; UserB sees there is one unread message without refresh his page and click to read it .
Again, pick the tool for the job. Knowing what your tools are is a good start. Socket.IO is meant to set up a communications channel between a server and a client. It provides web-socket-like functionality, commonly used between Node.js servers and web browsers (but can be used in other contexts as well!). Its two main features are that it provides fallback transports when Web Sockets are not available (making it compatible with old browsers), and it wraps up an event messaging system in some nice and simple calls. You don't have to worry about the underlying communication. Just emit and event on one end, and it is fired on the other. Simple.
For the actual communication between your servers and the browser, Socket.IO is an excellent choice. It provides near-real-time communication. However, Socket.IO isn't just some magic that will solve all of your problems for you. It would be useless to almost everyone if it were.
Since your messages need to persist, storing them in a database is a good idea. What I would do:
On message send, insert a copy into the database
On insert, fire a notice over your pub/sub to the other servers in your cluster
Any server that has a connection to the user getting the message will see this notice from the other server.
That server will load the user's message data out of the database and emit it over Socket.IO
You want a tutorial? The example on the Socket.IO home page is quite good: http://socket.io/

How does Facebook notify and instantly shows new comments or how does Stackoverflow do it?

I am a PHP developer and the title basically says it all. However I was hoping on some more in-depth information as I am starting to get confused about how the flow for the project I work on should go.
For an (web) application I need to implement a feature like Facebook does it with notifying users about replies/comments and instantly showing these.
I figured I could use long-polling with ajax requests but this does not seem to be a nice solution as the notifications never really are instant and it is resource heavy.
So I should use some form of sockets if I understand correctly, and Node.Js would be a good choice. So based on the last assumption I now get confused about the work flow.
I thought about two possible solutions:
1) It seems to me, that if I would use Node.Js I could skip using PHP at all and base the application on Node.js only.
2) Or I could use PHP as a base and only use Node.js for notifying users and instantly showing messages but saving the data using PHP and Mysql.
These two possibilities confuse me and I can't make up my mind about what would be the "best" and cleanest way.
I do not have much experience in Node.js, played with it for a while. But managing and saving data seems to be hard in Node.js so that is why I came up with option 2.
I know Facebook is build on PHP so I am assuming that they save the data via PHP and notify / instantly show replies and comments via Node.
Could someone help me out on this?
Thanks in advance!
EDIT:
I just noticed, Stackoverflow does something similar. I get a notification in the upper left, and below my question a box with "new answer to this question". I am really interested in the technologie(s) used.
Well you could use node.js for the notifications and PHP for your app.
By googling I found this about real-time-notifications.
You could also just use node.js with socket.io, but this means that you have to learn new technologies as you mention that you have no experience with node.
I haven't used it but you could check this project, for websockets in PHP.
When you have an update that you want to notify users you can use the publish subscriber pattern to notify the intrested in this update.
Take a look in Gearman too.
Personally, I've built a notification system using the pubsub mechanism of redis, with node.js+socket.io. Everytime that there is an update on a record then there is a publish on the appropriate channel. If the channel has listeners then they will be notified. I also store the last 20 notifications in a Redis list.
The appplication is built in PHP. The notification system is built in node.js. They are different applications that see the same data. The communication occurs via redis. For example in the Facebook context:
1) A user updates his status.
2) PHP stores this to the database and Redis
3) Redis knows that this update must publish to the status channel of the specific user and it does.
4) All the friends of the specific user are listening to his status channel (here comes node.js)
5) Node.js pushes the notification in the browser with socket.io
As for facebook, I have read in an article that is using long polling for supporting older browsers. Not sure for this though, needs citation...
AFAIK It would be via two simple methods :
First one that could be very simple is adding a Boolean column to each record that determines if it has been notified or not.
The second method is creating a table to insert all notifications.
However, I'm not sure if there are alternative methods for better performance, But first method is what I do commonly myself. But I think Facebook is using 2nd method, because it has to notify each one to a lot of users.
Your question maybe dublicate of:
Facebook like notifications tracking (DB Design)
Database design to store notifications to users
You could use Server Side Events it involves a bit of JavaScript but nothing overly complicated I think.
The main bulk of this method is PHP though, so you would just use the PHP to query your DB for notifications and SSE will push them to the user.
It does have some limitations though, most notably it's not supported by IE (huge surprise) thought i'd mention it anyway to let you know of other possibilities.
Hope this helps

Push notification to the client browser

I'd like to create an application where when a Super user clicks a link the users should get a notification or rather a content like a pdf for them to access on the screen.
Use Case: When a teacher wants to share a PDF with his students he should be able to notify his students about the pdf available for download and a link has to be provided to do the same.
There are several ways you can accomplish this. The most supported way is through a technique called Comet or long-polling. Basically, the client sends a request to the server and the server doesn't send a response until some event happens. This gives the illusion that the server is pushing to the client.
There are other methods and technologies that actually allow pushing to the client instead of just simulating it (i.e. Web Sockets), but many browsers don't support them.
As you want to implement this in CakePHP (so I assume it's a web-based application), the user will have to have an 'active' page open in order to receive the push messages.
It's worth looking at the first two answers to this, but also just think about how other sites might achieve this. Sites like Facebook, BBC, Stackoverflow all use techniques to keep pages up to date.
I suspect Facebook just uses some AJAX that runs in a loop/timer to periodically pull updates in a way that would make it look like push. If the update request is often enough (short time period), it'll almost look realtime. If it's a long time period it'll look like a pull. Finding the right balance between up-to-dateness and browser/processor/network thrashing is the key.
The actual request shouldn't thrash the system, but the reply in some applications may be much bigger. In your case, the data in each direction is tiny, so you could make the request loop quite short.
Experiment!
Standard HTTP protocol doesn't allow push from server to client. You can emulate this by using for example AJAX requests with small interval.
Have a look at php-amqplib and RabbitMQ. Together they can help you implement AMQP (Advanced Message Queuing Protocol). Essentially your web page can be made to update by pushing a message to it.
[EDIT] I recently came across Pusher which I have implemented for a project. It is a HTML5 WebSocket powered realtime messaging service. It works really well and has a free bottom tier plan. It's also extremely simple to implement.
Check out node.js in combination with socket.io and express. Great starting point here

Categories