【问题标题】:In perl socket programming how to send a data from client and receive it from server and how to get number of clients processes and client ID?在 perl 套接字编程中,如何从客户端发送数据并从服务器接收数据以及如何获取客户端进程数和客户端 ID?
【发布时间】:2019-09-19 18:44:24
【问题描述】:

如何获取连接到服务器的客户端数量?如果说我已经打开了 4 个终端并在 localhost 上运行了 4 次 client.pl 以进行测试,我如何在服务器脚本中获取客户端 ID 和客户端计数?我在 VirtualBox 上使用 Ubuntu。我在多线程环境中。

'''

#!/usr/bin/perl
#server
use warnings;
use strict;
use IO::Socket;
use threads;
use threads::shared;
$|++;
print "$$ Server started\n";;  # do a "top -p -H $$" to monitor server threads

our @clients : shared;
@clients = ();

my $server = new IO::Socket::INET(
    Timeout   => 7200,
    Proto     => "tcp",
    LocalPort => 9000,
    Reuse     => 1,
    Listen    => 3
);
my $num_of_client = -1;

while (1) {
    my $client;

    do {
        $client = $server->accept;
    } until ( defined($client) );

    my $peerhost = $client->peerhost();
    print "accepted a client $client, $peerhost, id = ", ++$num_of_client, "\n";
    my $fileno = fileno $client;
    push (@clients, $fileno);
    #spawn a thread here for each client
    my $thr = threads->new( \&processit, $client, $fileno, $peerhost )->detach(); 
}
# end of main thread

sub processit {
     my ($lclient,$lfileno,$lpeer) = @_; #local client

     if($lclient->connected){
          # Here you can do your stuff
          # I use have the server talk to the client
          # via print $client and while(<$lclient>)
          print $lclient "$lpeer->Welcome to server\n";  

          while(<$lclient>){
             # print $lclient "$lpeer->$_\n";
              print "clients-> @clients\n";           

              foreach my $fn (@clients) { 
                  open my $fh, ">&=$fn" or warn $! and die;
                  print $fh  "$_"  
                  }

           }

    }

  #close filehandle before detached thread dies out
  close( $lclient);
  #remove multi-echo-clients from echo list
  @clients = grep {$_ !~ $lfileno} @clients;

}
__END__

'''

【问题讨论】:

  • 我也应该在这里发布client.pl代码吗?
  • 您的代码已经有一个变量$num_clients。为什么不能用?
  • 好的。如何获取客户端 ID?我的意思是第一个连接的客户端应该被标记为 1,第二个被标记为 2,依此类推......我怎样才能做到这一点?
  • “我如何获取客户端 ID” 查看数组 @clients。第一个索引,索引 0 将对应 clinet #1,依此类推

标签: linux perl sockets tcp client-server


【解决方案1】:

将其与其余参数一起传递给 processit()。

【讨论】:

    猜你喜欢
    • 2014-09-09
    • 1970-01-01
    • 2013-04-01
    • 2010-10-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多