socket TCP server

programming/perl 2010. 5. 10. 11:01 |
http://www.tutorialspoint.com/perl/perl_socket.htm
##########server##########
#!/usr/bin/perl -w
# server.pl
#--------------------

use strict;
use Socket;

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

# create a socket, make it reusable
socket(SOCKET, PF_INET, SOCK_STREAM, $proto)
or die "Can't open socket $!\n";
setsockopt(SOCKET, SOL_SOCKET, SO_REUSEADDR, 1)
or die "Can't set socket option to SO_REUSEADDR $!\n";

# bind to a port, then listen
bind( SOCKET, pack( 'Sn4x8', AF_INET, $port, "\0\0\0\0" ))
or die "Can't bind to port $port! \n";
listen(SOCKET, 5) or die "listen: $!";
print "SERVER started on port $port\n";

# accepting a connection
my $client_addr;
while ($client_addr = accept(NET_SOCKET, SOCKET)) {
# send them a message, close connection
print NEW_SOCKET "Smile from the server";
close NEW_SOCKET;


}
##########client##########
#!/usr/bin/perl -w
# client.pl
#----------------

use strict;
use Socket;

# initialize host and port
my $host = shift || 'localhost';
my $port = shift || 7890;
my $server = "10.12.12.168";

# create the socket, connect to the port
socket(SOCKET,PF_INET,SOCK_STREAM,(getprotobyname('tcp'))[2])
or die "Can't create a socket $!\n";
connect( SOCKET, pack( 'Sn4x8', AF_INET, $port, $server ))
or die "Can't connect to port $port! \n";

my $line;
while ($line = <SOCKET>) {
print "$line\n";
}
close SOCKET or die "close: $!";

'programming > perl' 카테고리의 다른 글

echo server  (0) 2010.11.29
udp request  (0) 2010.05.10
tcp request  (0) 2010.05.10
외부파일실행예제  (0) 2010.04.28
웹페이지 긁어오기 예제  (0) 2010.04.09
Posted by applicationlayer
: