in reply to socket with threads problem
You seem to be trying to make two socket connections to the same port on the same host. What you'll need to do is to move the logic for the socket connections into each of the threads, setup individual server and client socket connections, and use the accept call to accept and handle the client connection.
Here's a working example, based on your code, with a few modifications:
use strict; use warnings; + use threads; use IO::Socket::INET; my $port = 1300; my $thread = threads->create("server_thread"); my $thread1 = threads->create("client_thread"); sub server_thread { my %params = ( LocalHost => '127.0.0.1', LocalPort => $port, Proto => 'tcp', Listen => 1, Reuse => 1, ReuseAddr => 1, ); my $so = new IO::Socket::INET(%params); die "Server Socket Error: $!\n" unless $so; print STDERR "[Server Socket Connected]\n"; + my $client = $so->accept(); $client->autoflush(1); + while (1) { my $txt = <$client>; last unless defined($txt); chomp $txt; last if ($txt eq 'quit'); print "server : $txt\n"; } print "[Server finished]\n"; } sub client_thread { sleep 1; # Give the server a head start my %params = ( 'PeerAddr' => '127.0.0.1', 'PeerPort' => $port, 'Proto' => 'tcp', 'ReuseAddr' => 1, ); my $so = new IO::Socket::INET(%params); $so->autoflush(1); die "Client Socket Error: $!\n" unless $so; print STDERR "[Client Socket Connected]\n"; while (my $msg = <STDIN>) { chomp $msg; last if ($msg eq 'quit'); print $so "$msg\n"; } print "[Client finished]\n"; } $thread->join(); $thread1->join();
The client thread waits for 1 second, to make sure the server thread has time to connect first. Then the server continues to fetch input from the filehandle returned by the accept call, until the user types "quit", at which point both the server and client threads finish.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: socket with threads problem
by wavenator (Novice) on Oct 10, 2007 at 17:59 UTC | |
by wavenator (Novice) on Oct 10, 2007 at 18:46 UTC |