Home » Php » How to implement a high performance asynchronous socket server application in PHP?

How to implement a high performance asynchronous socket server application in PHP?

Posted by: admin July 12, 2020 Leave a comment

Questions:

With nodejs, it’s very easy to create a non-blocking TCP server. Example from nodejs.org:

var net = require('net');
var server = net.createServer(function (socket) {
  socket.write("Echo server\r\n");
  socket.pipe(socket);
});
server.listen(1337, "127.0.0.1")

nodejs handles the select()-/poll()-/epoll() stuff for you, the socket routines and the main loop are implemented in C, so it’s very fast and efficient.

nodejs is great, but I’d like to implement a high performance TCP socket server in PHP, because I’m a PHP guy 🙂

So, one thing I already tried is to implement the socket routines in PHP, with socket_create_listen, socket_accept, socket_select etc. and the main loop in PHP. This works very well, but I don’t think it’s very efficient, because I have to use socket_select which calls the C-function select internally, but epoll would be better I think (I’m using Linux), but epoll is not available as PHP function.
(phpsocketdaemon and phpmio are 2 projects I found that implement the socket-routines for you).

Would it be possible to do it the nodejs way? I’m thinking about a PHP module that implements the loop and socket routines in C, and calls PHP callback functions for events (onread, onerror..). Or is it not worth the effort?

How to&Answers:

I think this is a typical case of “If all you have is a hammer, everything looks like a nail.”

As you yourself already figured out, php is not the right tool for the job. You can probably find a way to do it anyway, but it’ll most likely be messy.

So use the right tool for the job. You would not use a hammer to drive a screw into the wall, would you?