一个服务端 #!/cygdrive/c/Perl/bin/perl -w use strict; use warnings; use IO::Socket; use Tk; sub sendf{ my $socket=IO::Socket::INET->;new( PeerHost => 'localhost', Protor => "tcp", PeerPort => 3067 ); die "no socket $@ \n" until $socket; print "client created \n"; print $socket "client say: ".shift."\n"; $socket->;flush(); close($socket); } my $mw = MainWindow->;new; $mw->;Button( -text=>"say hello", -command=>sub{sendf("Hello, server!");} )->pack; MainLoop; 一个客户端(只有一个按钮,按一下,就去跟服务器发消息) #!/cygdrive/c/Perl/bin/perl use strict; use warnings; use Tk; use IO::Socket; my $socket = IO::Socket::INET->;new( LocalHost => 'localhost', Proto => "tcp", LocalPort => 3067, Listen => 5 ) or die 'no socket $@ \n'; print "server created \n"; while(my $nsocket = $socket->;accept()){ while(defined (my $buf = <$nsocket>;)) { print "\n$buf"; } } close($socket); print "server finished\n";注意
服务器端 socket 创建时,listen 参数一定要设定,否则不会报错,但服务器不会被 accept() 阻塞
没有评论:
发表评论