Chinaunix首页 | 论坛 | 博客
  • 博客访问: 858703
  • 博文数量: 253
  • 博客积分: 6891
  • 博客等级: 准将
  • 技术积分: 2502
  • 用 户 组: 普通用户
  • 注册时间: 2010-11-03 11:01
文章分类

全部博文(253)

文章存档

2016年(4)

2013年(3)

2012年(32)

2011年(184)

2010年(30)

分类: Python/Ruby

2011-11-08 14:11:10

  1. #!/usr/bin/perl -w
  2. #
  3. use strict;
  4. use IO::Handle;
  5. use Socket;

  6. my ($bytes_out, $bytes_in) = (0,0);

  7. my $host = shift || 'localhost';
  8. my $port = shift || getservbyname('echo', 'tcp');

  9. my $protocol = getprotobyname('tcp');

  10. socket(SOCK, AF_INET, SOCK_STREAM, $protocol) or die 'sock() failed: $!';
  11. my $packed_add = inet_aton($host);
  12. my $dest_add = sockaddr_in($port, $packed_add);

  13. connect(SOCK, $dest_add) or die "connet() failed: $!";

  14. SOCK->autoflush(1);

  15. while( 1 ){
  16.         print "Client:";
  17.         my $msg_out = <>;
  18. #print SOCK "Client:".$msg_out;
  19.         send(SOCK, "Client:".$msg_out, 0);
  20.         my $msg_in = <SOCK>;
  21.         print $msg_in;

  22.         $bytes_out += length($msg_out);
  23. #$bytes_in += length($msg_in);

  24. }

  25. close SOCK;
  26. #print STDERR "bytes_sent = $bytes_out, bytes_received = $bytes_in\n";

server:
  1. #!/usr/bin/perl -w
  2. #
  3. use strict;
  4. use Socket;
  5. use IO::Handle;

  6. my ($bytes_in, $bytes_out) = (0, 0);
  7. my $port = shift || '3000';
  8. my $protocol = getprotobyname('tcp');

  9. socket(SOCK, AF_INET, SOCK_STREAM, $protocol) or die "socket() failed:$!";
  10. setsockopt(SOCK, SOL_SOCKET, SO_REUSEADDR, 1) or die " canot set so_reuseadd:$!";

  11. my $my_addr = sockaddr_in($port, INADDR_ANY);
  12. bind(SOCK, $my_addr) or die"bind() failed: $!";
  13. listen(SOCK, SOMAXCONN) or die "listen() failed: $!";

  14. warn "waiting for incoming connections on port $port ...\n";

  15. while(1){
  16.         next unless my $remote_addr = accept(SESSION, SOCK);
  17.         my ($port, $hisaddr) = sockaddr_in($remote_addr);
  18.         warn "Connection from [", inet_ntoa($hisaddr), ", $port]\n";

  19.         SESSION->autoflush(1);
  20.         while(<SESSION>){
  21.                 $bytes_in += length($_);
  22.                 chomp;
  23.                 print $_."\n";

  24. #my $msg_out = (scalar reverse $_) . "\n";
  25.                 print "Server:";
  26.                 my $msg_out = <>;
  27.                 print SESSION "Server:".$msg_out;
  28.                 $bytes_out += length($msg_out);
  29.         }
  30.         warn " Connection from [", inet_ntoa($hisaddr), ", $port] finished\n";
  31.         close SESSION;

  32. }

  33. close SOCK;




阅读(142898) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~