Note that there are some explanatory texts on larger screens.

plurals
  1. POHow do I save sockets in a hash and loop over them from another thread?
    primarykey
    data
    text
    <p>I am working on a mulithreaded TCP server. In the main thread, I listen on a socket and create a new thread for new incoming connections. I want to save all incoming connections in a hash so that I can access them from yet another thread.</p> <p>From the monitor thread, I can not read any newly added connections. It seems a new clients hash is created when creating the monitor thread.</p> <p>How do i keep list of all sockets and loop them from my monitor thread?</p> <p>Current code:</p> <pre><code>#!/usr/bin/perl use strict; use IO::Socket; use threads; use Thread::Queue; # init my $clients = {}; my $queue = Thread::Queue-&gt;new; # thread that monitors threads-&gt;create("monitor"); # create the listen socket my $listenSocket = IO::Socket::INET-&gt;new(LocalPort =&gt; 12345, Listen =&gt; 10, Proto =&gt; 'tcp', Reuse =&gt; 1); # make sure we are bound to the port die "Cant't create a listening socket: $@" unless $listenSocket; print "Server ready. Waiting for connections on 34567 ... \n"; # wait for connections at the accept call while (my $connection = $listenSocket-&gt;accept) { # set client socket to non blocking my $nonblocking = 1; ioctl($connection, 0x8004667e, \\$nonblocking); # autoflush $connection-&gt;autoflush(1); # debug print "Accepted new connection\n"; # add to list $clients-&gt;{time()} = $connection; # start new thread and listen on the socket threads-&gt;create("readData", $connection); } sub readData { # socket parameter my ($client) = @_; # read client while (&lt;$client&gt;) { # remove newline chomp $_; # add to queue $queue-&gt;enqueue($_); } close $client; } sub monitor { # endless loop while (1) { # loop while there is something in the queue while ($queue-&gt;pending) { # get data from a queue my $data = $queue-&gt;dequeue; # loop all sockets while ( my ($key, $value) = each(%$clients) ) { # send to socket print $value "$data\n"; } } # wait 0,25 seconds select(undef, undef, undef, 0.25); } } close $listenSocket; </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload