Sie sind auf Seite 1von 2

Server Code

------------

1. #! /usr/bin/perl -w
2. # server0.pl
3. #--------------------

4. use strict;
5. use Socket;

6. # use port 7890 as default
7. my $port = shift || 7890;
8. my $proto = getprotobyname('tcp');

9. # create a socket, make it reusable
10. socket(SERVER, PF_INET, SOCK_STREAM, $proto) or die "socket: $!";
11. setsockopt(SERVER, SOL_SOCKET, SO_REUSEADDR, 1) or die "setsock: $!";

12. # grab a port on this machine
13. my $paddr = sockaddr_in($port, INADDR_ANY);

14. # bind to a port, then listen
15. bind(SERVER, $paddr) or die "bind: $!";
16. listen(SERVER, SOMAXCONN) or die "listen: $!";
17. print "SERVER started on port $port ";

18. # accepting a connection
19. my $client_addr;
20. while ($client_addr = accept(CLIENT, SERVER))
21. {
22. # find out who connected
23. my ($client_port, $client_ip) = sockaddr_in($client_addr);
24. my $client_ipnum = inet_ntoa($client_ip);
25. my $client_host = gethostbyaddr($client_ip, AF_INET);
26. # print who has connected
27. print "got a connection from: $client_host","[$client_ipnum] ";
28. # send them a message, close connection
29. print CLIENT "Smile from the server";
30. close CLIENT;
31. }


Client Code:
-------------
1. #! /usr/bin/perl -w
2. # client1.pl - a simple client
3. #----------------

4. use strict;
5. use Socket;

6. # initialize host and port
7. my $host = shift || 'localhost';
8. my $port = shift || 7890;

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

10. # get the port address
11. my $iaddr = inet_aton($host);
12. my $paddr = sockaddr_in($port, $iaddr);
Page 1 of 2
2/6/2009 http://10.203.161.13/download/client_server.txt?id=uniqueid
13. # create the socket, connect to the port
14. socket(SOCKET, PF_INET, SOCK_STREAM, $proto)
a. or die "socket: $!";
15. connect(SOCKET, $paddr) or die "connect: $!";

16. my $line;
17. while ($line = )
18. {
19. print $line;
20. }
21. close SOCKET or die "close: $!";
Page 2 of 2
2/6/2009 http://10.203.161.13/download/client_server.txt?id=uniqueid

Das könnte Ihnen auch gefallen