L
L
Lander2016-07-24 15:22:53
PHP
Lander, 2016-07-24 15:22:53

How to work with sockets in multiple threads?

Good afternoon!
I thought for a long time whether to ask a question or not, since he is very noob, but in the end he decided.
In general, I decided to learn how to work with sockets and write a simple chat as an introduction. I chose PHP as a base (I know that it’s not the best choice, but I didn’t want to remember C ++ and install the studio).
I work as standard as it is written in the documentation and examples:

$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
...
socket_bind($socket, $address, $port);
...
socket_listen($socket, 10);
...
  while (true) {
  $connect = socket_accept($socket);
  $result = socket_read($connect,1024);
  echo 'Common data: '.$result."\r\n";
  socket_write($connect,'You sending me: '.$result."\r\n");
  socket_shutdown($connect);
  }

When connecting to this socket on the client, everything is worked out, but as soon as I try to connect the second client, until the first connection is closed, it hangs and cannot connect until socket_shutdown ($ connect); is executed for the first one;
In this regard, the question is: How can I organize work with several connections at the same time? Otherwise, it turns out that each client, in order to receive messages from other clients, must reconnect and request these messages.
I'm trying to create multiple sockets on the same port, but for obvious reasons I'm not allowed to do so.
I found an example on the Internet in php, but the link to the code turned out to be broken.
Thanks in advance to all who answer.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
Vladimir Dubrovin, 2016-07-24
@usdglander

There are 3 main approaches.
1. What you mean is that after accept(), create a separate thread for each client and process the incoming connection in it.
2. Use a single thread, set sockets to non-blocking mode, and use select() or poll() / epol() / ... to detect data coming into the socket and process it
3. Use a multi-worker model. Run several worker threads working in the same way as in paragraph 2, distribute incoming connections between them. Usually servers write this way for a fairly large load.
A fairly detailed answer is here: https://www.opennet.ru/base/faq/prog_faq.txt.html , see "how to write servers".

L
Lander, 2016-07-24
@usdglander

Correct me if I'm wrong:

$clients = array();
$socket = socket_create(AF_INET,SOCK_STREAM,SOL_TCP);
socket_bind($socket,'127.0.0.1',$port);
socket_listen($socket);
socket_set_nonblock($socket);

while(true)
{
    if(($newc = socket_accept($socket)) !== false)
    {
        echo "Client $newc has connected\n";
        $clients[] = $newc;
    }
}

That is, I then just need to bypass the $clients array, and read and send data somehow, right?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question