Hi
My problem is to write a server script which processes incoming queries and responds to them in the usual way ... but also runs a periodic "report" function where it talks back at the client of its own accord. The report code is therefore a seperate thread.
The problem is that I don't find a way to allow the main and reporting threads to both talk back at the client. What seems to happen is that when I hasve the "write to socket" happening in both threads, they block each other in odd ways. (The report lines seem to appear after the first char of a client line is entered.)
This may be only a win32 problem, haven't tried on linux yet.
Here's my first attempt:
use strict; use warnings; use threads; use IO::Socket qw(:DEFAULT :crlf); use Time::HiRes qw( usleep ); my $sock = new IO::Socket::INET (LocalAddr => "localhost", LocalPort => 1000, Proto => 'tcp', Listen => 1, Reuse => 1); my $SOCK; sub sockout{ my $r = shift; print $SOCK "$r\r\n"; } sub chatter{ while (1){ usleep(1000 * 1000); sockout "talkin to myself ..."; } } $SOCK = $sock->accept(); my $thread = threads->create(\&chatter); sockout("CONNECTED!"); while (my $line = <$SOCK>){ sockout("You said ".$line); }
One suggestion that has been made is to use a queue. I tried, same problem. Here it is:
use strict; use warnings; use threads; use Thread::Queue; use IO::Socket qw(:DEFAULT :crlf); use Time::HiRes qw( usleep ); my $sock = new IO::Socket::INET (LocalAddr => "localhost", LocalPort => 1000, Proto => 'tcp', Listen => 1, Reuse => 1); my $SOCK; my $rq; sub sockout{ my $r = shift; print $SOCK "$r\r\n"; } sub chatter{ while (1){ usleep(1000 * 1000); sockout "talkin to myself ..."; } } sub reply_thread{ while (1){ while ($rq->pending){ print "rt pr\n"; print $SOCK $rq->dequeue; }; usleep(1000 * 100); } } $SOCK = $sock->accept(); $rq = new Thread::Queue; my $reply_thread = threads->create(\&reply_thread); my $chatter_thread = threads->create(\&chatter); sockout("CONNECTED!"); while (my $line = <$SOCK>){ sockout("You said ".$line); }
Any ideas?
In reply to sharing a socket between two threads (win32) by danmcb
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |