LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   PHP - Multithreaded Sockets (https://www.linuxquestions.org/questions/programming-9/php-multithreaded-sockets-600745/)

baddah 11-19-2007 01:09 AM

PHP - Multithreaded Sockets
 
Hi,

I want to have a client socket that connects to a server,and will always listen for incoming commands from the server,BUT it needs to check at the same time if it has something to send to the server.This is done by looking at a MySQL Queue table i populate with commands i need to send the server.

Is this possible in PHP,i.e

thread 1 => Listen for and handle incoming commands
thread 2 => Check for and handle outgoing commands.

If i receive commands while i'm busy sending,my script must be able to process incoming commands as well.

The reason i want to use PHP,is because a lot of the commands is MySQL dependant,i.e there is a lot of queries,selects,etc,and i would really prefer to use PHP for this rather than C or Java.

If this is not possible in PHP,what language should i rather use?Maybe Perl would be easier,but PHP would be my first option?

Any suggestions?

chrism01 11-19-2007 01:14 AM

Don't know about PHP, but Perl can definitely do thrs and MySQL etc. Done it myself... Just use the pre-written CPAN modules here: http://search.cpan.org/

Guttorm 11-19-2007 02:24 AM

Hi

PHP doesn't have threads, but it can fork. See http://www.php.net/manual/en/function.pcntl-fork.php

Note that after a fork, you get a new process, not a thread, so any communication between the processes has to be coded by yourself.

baddah 11-19-2007 02:26 AM

Hi,

Thanks for your reply.I've got the MySQL part and the Socket part working,but i'm not sure what i need to do for multithreading.Can you maybe direct me to a small example where this is done.Here is my simple client,without multi threading enabled.I marked where i'd like the two threads to run.

Code:

use DBI;
use IO::Socket::INET;

# Create a new socket
$MySocket=new IO::Socket::INET->new(PeerPort=>1234,Proto=>'tcp',PeerAddr=>'192.168.100.58');
$db = DBI->connect("dbi:mysql:database:localhost","root","");

# loop for ever
while (1) {

        # loop every 1 second
        sleep(1);
        #Thread 1 Check if there is messages to send to server socket

        $sql = "select * from queuetable";
        $sql = $db->prepare($sql);
        $sql->execute;

        while(@data = $sql->fetchrow_array) {

                $message = $data[0];
                $MySocket->send($message);
        }

        #Thread 2 Check for incoming messages from server and display it
        $MySocket->recv($received,1024);
        print "$received";
}


chrism01 11-19-2007 11:06 PM

Start by reading this: http://perldoc.perl.org/perlthrtut.html


All times are GMT -5. The time now is 02:30 PM.