Answer the question
In order to leave comments, you need to log in
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);
}
Answer the question
In order to leave comments, you need to log in
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".
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;
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question