SlideShare ist ein Scribd-Unternehmen logo
1 von 22
Downloaden Sie, um offline zu lesen
Perl Programming
                 Course
            Network programming




Krassimir Berov

I-can.eu
Contents
1. Sockets, servers and clients
2. TCP/IP, UDP sockets
3. Unix Domain Socket (UDS) sockets
4. IO::Socket
5. HTTP and SMTP
6. LWP and WWW::Mechanize
Sockets, servers and clients

• Socket
  • an end-point of a bi-directional communication link
    in the Berkeley sockets API
  • Berkeley sockets API allows communications
    between hosts or between processes on one
    computer
  • One of the fundamental technologies underlying the
    Internet.
  • A network socket is a communication end-point
    unique to a machine communicating on an Internet
    Protocol-based network, such as the Internet.
  • Unix domain socket, an end-point
    in local inter-process communication
Sockets, servers and clients

• Server
  • An application or device that performs
    services for connected clients as part of a
    client-server architecture
  • An application program that accepts
    connections in order to service requests by
    sending back responses
  • Example:
    web servers(Apache), e-mail servers(Postfix),
    file servers
Sockets, servers and clients

• Client
  • An application or system that accesses a
    (remote) service on another computer
    system known as a server
  • Example:
    Web browsers (Internet Explorer, Opera,
    Firefox)
    Mail Clients (Thunderbird, KMail, MS
    Outlook)
TCP/IP, UDP sockets
• An Internet socket is composed of
  • Protocol (TCP, UDP, raw IP)
  • Local IP address
  • Local port
  • Remote IP address
  • Remote port
Unix Domain Socket
• A Unix domain socket (UDS)
  or IPC socket
  • inter-process communication socket
  • a virtual socket
  • similar to an internet socket
  • used in POSIX operating systems for inter-
    process communication
     • connections appear as byte streams, much like
       network connections,
     • all data remains within the local computer
IO::Socket
• IO::Socket - Object interface to socket
  communications
  • built upon the IO::Handle interface and inherits
    all its methods
  • only defines methods for operations common to
    all types of socket
  • Operations, specified to a socket in a particular
    domain have methods defined in sub classes
  • will export all functions (and constants) defined
    by Socket
IO::Socket
• IO::Socket – Example (TCP/IP)
  #io-socket-tcp-client.pl
  use IO::Socket;
  my $sock = IO::Socket::INET->new(
      PeerAddr => $host,
      PeerPort => "$port",
      Proto => 'tcp',
      Timeout => 60
  ) or die $@;

  die "Could not connect to $host$/"
      unless $sock->connected;

  #...
IO::Socket
• IO::Socket – Example 2 (TCP/IP)
  #io-socket-tcp-server.pl
  use IO::Socket;
  my ($host, $port, $path ) = ( 'localhost', 8088 );
  my $server = new IO::Socket::INET (
       LocalAddr => $host,
       LocalPort => $port,
       Proto => 'tcp',
       Listen => 10,
       Type      => SOCK_STREAM,
       ReuseAddr => 1
  );
  print "Server ($0) running on port $port...n";
  while (my $connection = $server->accept) {
  #...
IO::Socket
• IO::Socket – Example (UDS)
 #io-socket-uds-server.pl
 use IO::Socket;
 my $file = "./udssock";
 unlink $file;
 my $server = IO::Socket::UNIX->new(
     Local => $file,
     Type   => SOCK_STREAM,
     Listen => 5
 ) or die $@;

 print "Server running on file $file...n";
 #...
IO::Socket
• IO::Socket – Example 2 (UDS)
 #io-socket-uds-client.pl
 use IO::Socket;
 my $server = IO::Socket::UNIX->new(
     Peer => "./udssock",
 ) or die $@;

 # communicate with the server
 print "Client connected.n";
 print "Server says: ", $server->getline;
 $server->print("Hello from the client!n");
 $server->print("And goodbye!n");
 $server->close;
 #...
IO::Socket
• IO::Socket – Example (UDP)
 #io-socket-udp-server.pl
 use IO::Socket;
 my $port = 4444;
 my $server = new IO::Socket::INET(
    LocalPort => $port,
    Proto     => 'udp',
 );
 die "Bind failed: $!n" unless $server;
 print "Server running on port $port...n";
 #...
IO::Socket
• IO::Socket – Example 2 (UDP)
 #io-socket-udp-client.pl
 use IO::Socket;
 my $host = 'localhost';
 my $port = 4444;
 my $client = new IO::Socket::INET(
      PeerAddr => $host,
      PeerPort => $port,
      Timeout => 2,
      Proto    => 'udp',
 );
 $client->send("Hello from client") or die "Send: $!n";
 my $message;
 $client->recv($message, 1024, 0);
 print "Response was: $messagen";
 #...
HTTP and SMTP
• HTTP
• SMTP
Sending Mail
• Net::SMTP
 #smtp.pl
 use Net::SMTP;
 my $smtp = Net::SMTP->new(
     Host => 'localhost',
     Timeout => 30,
     Hello =>'localhost',
 );
 my $from = 'me@example.com';
 my @to   = ('you@example.org',);
 my $text = $ARGV[0]|| 'проба';
 my $mess = "ERROR: Can't send mail using Net::SMTP. ";
 $smtp->mail( $from ) || die $mess;
 $smtp->to( @to, { SkipBad => 1 } ) || die $mess;
 $smtp->data( $text ) || die $mess;
 $smtp->dataend() || die $mess;
 $smtp->quit();
LWP and WWW::Mechanize
• LWP - The World-Wide Web library for Perl
  • provides a simple and consistent application
    programming interface (API)
    to the World-Wide Web
  • classes and functions that allow you to write
    WWW clients
  • also contains modules that help you implement
    simple HTTP servers
  • supports access to http, https, gopher, ftp, news,
    file, and mailto resources
  • transparent redirect, parser for robots.txt files
    etc...
LWP and WWW::Mechanize
• WWW::Mechanize - Handy web browsing in a
  Perl object
  • helps you automate interaction with a website

  • well suited for use in testing web applications

  • is a proper subclass of LWP::UserAgent

  • you can also use any of the LWP::UserAgent's
    methods.
LWP and WWW::Mechanize
• WWW::Mechanize - Example
  • helps you automate interaction with a website

  • well suited for use in testing web applications

  • is a proper subclass of LWP::UserAgent

  • you can also use any of the LWP::UserAgent's
    methods.
LWP and WWW::Mechanize
• Example – getting product data from a site
 #www_mech.pl
 use strict; use warnings;
 use MyMech;
 use Data::Dumper;
 #Config
 $MyMech::Config->{DEBUG}=0;
 my $Config = $MyMech::Config;
 #print Dumper($Config);
 my $mech = MyMech->new(
      agent      => $Config->{agent},
      cookie_jar => $Config->{cookie_jar},
      autocheck => $Config->{autocheck},
      onwarn     => $Config->{onwarn}
 );
 #...
Network programming
• Resources
  • Beginning Perl
    (Chapter 14 – The World of Perl/IPC and
    Networking)
  • Professional Perl Programming
    (Chapter 23 – Networking with Perl)
  • perldoc perlipc
  • perldoc IO::Socket
  • http://en.wikipedia.org/wiki/Berkeley_sockets
  • Perl & LWP (http://lwp.interglacial.com/)
Network programming




Questions?

Weitere ähnliche Inhalte

Was ist angesagt?

Chapter03 Creating And Managing User Accounts
Chapter03      Creating And  Managing  User  AccountsChapter03      Creating And  Managing  User  Accounts
Chapter03 Creating And Managing User Accounts
Raja Waseem Akhtar
 
introduction to web technology
introduction to web technologyintroduction to web technology
introduction to web technology
vikram singh
 
Introduction to Web Programming - first course
Introduction to Web Programming - first courseIntroduction to Web Programming - first course
Introduction to Web Programming - first course
Vlad Posea
 
Linux process management
Linux process managementLinux process management
Linux process management
Raghu nath
 

Was ist angesagt? (20)

Windows Server 2019 -InspireTech 2019
Windows Server 2019 -InspireTech 2019Windows Server 2019 -InspireTech 2019
Windows Server 2019 -InspireTech 2019
 
Linux Directory Structure
Linux Directory StructureLinux Directory Structure
Linux Directory Structure
 
Understanding the Windows Server Administration Fundamentals (Part-1)
Understanding the Windows Server Administration Fundamentals (Part-1)Understanding the Windows Server Administration Fundamentals (Part-1)
Understanding the Windows Server Administration Fundamentals (Part-1)
 
Chapter03 Creating And Managing User Accounts
Chapter03      Creating And  Managing  User  AccountsChapter03      Creating And  Managing  User  Accounts
Chapter03 Creating And Managing User Accounts
 
Disk formatting
Disk formattingDisk formatting
Disk formatting
 
operating system pdf
operating system pdfoperating system pdf
operating system pdf
 
Introduction to ASP.NET
Introduction to ASP.NETIntroduction to ASP.NET
Introduction to ASP.NET
 
System Administration: Introduction to system administration
System Administration: Introduction to system administrationSystem Administration: Introduction to system administration
System Administration: Introduction to system administration
 
File System Implementation - Part1
File System Implementation - Part1File System Implementation - Part1
File System Implementation - Part1
 
Php
PhpPhp
Php
 
Linux LVM Logical Volume Management
Linux LVM Logical Volume ManagementLinux LVM Logical Volume Management
Linux LVM Logical Volume Management
 
introduction to web technology
introduction to web technologyintroduction to web technology
introduction to web technology
 
ASP.NET Tutorial - Presentation 1
ASP.NET Tutorial - Presentation 1ASP.NET Tutorial - Presentation 1
ASP.NET Tutorial - Presentation 1
 
Command prompt presentation
Command prompt presentationCommand prompt presentation
Command prompt presentation
 
Introduction to Web Programming - first course
Introduction to Web Programming - first courseIntroduction to Web Programming - first course
Introduction to Web Programming - first course
 
Introduction to Operating Systems
Introduction to Operating SystemsIntroduction to Operating Systems
Introduction to Operating Systems
 
Fundamentals of Database system
Fundamentals of Database systemFundamentals of Database system
Fundamentals of Database system
 
Unix - An Introduction
Unix - An IntroductionUnix - An Introduction
Unix - An Introduction
 
Exploring the Oracle Database Architecture.ppt
Exploring the Oracle Database Architecture.pptExploring the Oracle Database Architecture.ppt
Exploring the Oracle Database Architecture.ppt
 
Linux process management
Linux process managementLinux process management
Linux process management
 

Andere mochten auch

Aulas de Java Avançado 2- Faculdade iDez 2010
Aulas de Java Avançado 2- Faculdade iDez 2010Aulas de Java Avançado 2- Faculdade iDez 2010
Aulas de Java Avançado 2- Faculdade iDez 2010
Maurício Linhares
 
Linguagem PHP para principiantes
Linguagem PHP para principiantesLinguagem PHP para principiantes
Linguagem PHP para principiantes
Marco Pinheiro
 
Socket programming with php
Socket programming with phpSocket programming with php
Socket programming with php
Elizabeth Smith
 
correção Ficha 4,5,6,e 7
correção Ficha 4,5,6,e 7correção Ficha 4,5,6,e 7
correção Ficha 4,5,6,e 7
edlander
 
Programming TCP/IP with Sockets
Programming TCP/IP with SocketsProgramming TCP/IP with Sockets
Programming TCP/IP with Sockets
elliando dias
 

Andere mochten auch (17)

Sockets
SocketsSockets
Sockets
 
Aulas de Java Avançado 2- Faculdade iDez 2010
Aulas de Java Avançado 2- Faculdade iDez 2010Aulas de Java Avançado 2- Faculdade iDez 2010
Aulas de Java Avançado 2- Faculdade iDez 2010
 
Pyhug zmq
Pyhug zmqPyhug zmq
Pyhug zmq
 
Aula sockets
Aula socketsAula sockets
Aula sockets
 
Aplicações Web Ricas e Acessíveis
Aplicações Web Ricas e AcessíveisAplicações Web Ricas e Acessíveis
Aplicações Web Ricas e Acessíveis
 
Lidando com Erros - Android
Lidando com Erros - AndroidLidando com Erros - Android
Lidando com Erros - Android
 
Linguagem PHP
Linguagem PHPLinguagem PHP
Linguagem PHP
 
Linguagem PHP para principiantes
Linguagem PHP para principiantesLinguagem PHP para principiantes
Linguagem PHP para principiantes
 
Módulo-6-7-ip-com-sockets
Módulo-6-7-ip-com-socketsMódulo-6-7-ip-com-sockets
Módulo-6-7-ip-com-sockets
 
Tecnologia java para sockets
Tecnologia java para socketsTecnologia java para sockets
Tecnologia java para sockets
 
Redes 1 - Sockets em C#
Redes 1 - Sockets em C#Redes 1 - Sockets em C#
Redes 1 - Sockets em C#
 
Socket programming with php
Socket programming with phpSocket programming with php
Socket programming with php
 
correção Ficha 4,5,6,e 7
correção Ficha 4,5,6,e 7correção Ficha 4,5,6,e 7
correção Ficha 4,5,6,e 7
 
Programming TCP/IP with Sockets
Programming TCP/IP with SocketsProgramming TCP/IP with Sockets
Programming TCP/IP with Sockets
 
Basic socket programming
Basic socket programmingBasic socket programming
Basic socket programming
 
Socket programming
Socket programmingSocket programming
Socket programming
 
Socket Programming Tutorial
Socket Programming TutorialSocket Programming Tutorial
Socket Programming Tutorial
 

Ähnlich wie Network programming

Running Head IMPLEMENTING THE LIST AND SEARCH FEATURES IN THE DIS.docx
Running Head IMPLEMENTING THE LIST AND SEARCH FEATURES IN THE DIS.docxRunning Head IMPLEMENTING THE LIST AND SEARCH FEATURES IN THE DIS.docx
Running Head IMPLEMENTING THE LIST AND SEARCH FEATURES IN THE DIS.docx
cowinhelen
 
AnyMQ, Hippie, and the real-time web
AnyMQ, Hippie, and the real-time webAnyMQ, Hippie, and the real-time web
AnyMQ, Hippie, and the real-time web
clkao
 
Puppet Camp Charlotte 2015: Exporting Resources: There and Back Again
Puppet Camp Charlotte 2015: Exporting Resources: There and Back AgainPuppet Camp Charlotte 2015: Exporting Resources: There and Back Again
Puppet Camp Charlotte 2015: Exporting Resources: There and Back Again
Puppet
 

Ähnlich wie Network programming (20)

A.java
A.javaA.java
A.java
 
Exploring Async PHP (SF Live Berlin 2019)
Exploring Async PHP (SF Live Berlin 2019)Exploring Async PHP (SF Live Berlin 2019)
Exploring Async PHP (SF Live Berlin 2019)
 
java networking
 java networking java networking
java networking
 
2019 11-bgphp
2019 11-bgphp2019 11-bgphp
2019 11-bgphp
 
Introduction to Node.js: What, why and how?
Introduction to Node.js: What, why and how?Introduction to Node.js: What, why and how?
Introduction to Node.js: What, why and how?
 
Running Head IMPLEMENTING THE LIST AND SEARCH FEATURES IN THE DIS.docx
Running Head IMPLEMENTING THE LIST AND SEARCH FEATURES IN THE DIS.docxRunning Head IMPLEMENTING THE LIST AND SEARCH FEATURES IN THE DIS.docx
Running Head IMPLEMENTING THE LIST AND SEARCH FEATURES IN THE DIS.docx
 
Learn Electron for Web Developers
Learn Electron for Web DevelopersLearn Electron for Web Developers
Learn Electron for Web Developers
 
Rack
RackRack
Rack
 
Rails web api 开发
Rails web api 开发Rails web api 开发
Rails web api 开发
 
Socket programming-tutorial-sk
Socket programming-tutorial-skSocket programming-tutorial-sk
Socket programming-tutorial-sk
 
AnyMQ, Hippie, and the real-time web
AnyMQ, Hippie, and the real-time webAnyMQ, Hippie, and the real-time web
AnyMQ, Hippie, and the real-time web
 
Write php deploy everywhere tek11
Write php deploy everywhere   tek11Write php deploy everywhere   tek11
Write php deploy everywhere tek11
 
Python, do you even async?
Python, do you even async?Python, do you even async?
Python, do you even async?
 
Asynchronous PHP and Real-time Messaging
Asynchronous PHP and Real-time MessagingAsynchronous PHP and Real-time Messaging
Asynchronous PHP and Real-time Messaging
 
Service Discovery using etcd, Consul and Kubernetes
Service Discovery using etcd, Consul and KubernetesService Discovery using etcd, Consul and Kubernetes
Service Discovery using etcd, Consul and Kubernetes
 
Automating Complex Setups with Puppet
Automating Complex Setups with PuppetAutomating Complex Setups with Puppet
Automating Complex Setups with Puppet
 
How to automate all your SEO projects
How to automate all your SEO projectsHow to automate all your SEO projects
How to automate all your SEO projects
 
Nodejs Explained with Examples
Nodejs Explained with ExamplesNodejs Explained with Examples
Nodejs Explained with Examples
 
Nodejsexplained 101116115055-phpapp02
Nodejsexplained 101116115055-phpapp02Nodejsexplained 101116115055-phpapp02
Nodejsexplained 101116115055-phpapp02
 
Puppet Camp Charlotte 2015: Exporting Resources: There and Back Again
Puppet Camp Charlotte 2015: Exporting Resources: There and Back AgainPuppet Camp Charlotte 2015: Exporting Resources: There and Back Again
Puppet Camp Charlotte 2015: Exporting Resources: There and Back Again
 

Mehr von Krasimir Berov (Красимир Беров)

Mehr von Krasimir Berov (Красимир Беров) (15)

Хешове
ХешовеХешове
Хешове
 
Списъци и масиви
Списъци и масивиСписъци и масиви
Списъци и масиви
 
Скаларни типове данни
Скаларни типове данниСкаларни типове данни
Скаларни типове данни
 
Въведение в Perl
Въведение в PerlВъведение в Perl
Въведение в Perl
 
System Programming and Administration
System Programming and AdministrationSystem Programming and Administration
System Programming and Administration
 
Processes and threads
Processes and threadsProcesses and threads
Processes and threads
 
Working with databases
Working with databasesWorking with databases
Working with databases
 
Working with text, Regular expressions
Working with text, Regular expressionsWorking with text, Regular expressions
Working with text, Regular expressions
 
Subroutines
SubroutinesSubroutines
Subroutines
 
IO Streams, Files and Directories
IO Streams, Files and DirectoriesIO Streams, Files and Directories
IO Streams, Files and Directories
 
Syntax
SyntaxSyntax
Syntax
 
Hashes
HashesHashes
Hashes
 
Lists and arrays
Lists and arraysLists and arrays
Lists and arrays
 
Scalar data types
Scalar data typesScalar data types
Scalar data types
 
Introduction to Perl
Introduction to PerlIntroduction to Perl
Introduction to Perl
 

Kürzlich hochgeladen

Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
WSO2
 

Kürzlich hochgeladen (20)

Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdf
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 

Network programming

  • 1. Perl Programming Course Network programming Krassimir Berov I-can.eu
  • 2. Contents 1. Sockets, servers and clients 2. TCP/IP, UDP sockets 3. Unix Domain Socket (UDS) sockets 4. IO::Socket 5. HTTP and SMTP 6. LWP and WWW::Mechanize
  • 3. Sockets, servers and clients • Socket • an end-point of a bi-directional communication link in the Berkeley sockets API • Berkeley sockets API allows communications between hosts or between processes on one computer • One of the fundamental technologies underlying the Internet. • A network socket is a communication end-point unique to a machine communicating on an Internet Protocol-based network, such as the Internet. • Unix domain socket, an end-point in local inter-process communication
  • 4. Sockets, servers and clients • Server • An application or device that performs services for connected clients as part of a client-server architecture • An application program that accepts connections in order to service requests by sending back responses • Example: web servers(Apache), e-mail servers(Postfix), file servers
  • 5. Sockets, servers and clients • Client • An application or system that accesses a (remote) service on another computer system known as a server • Example: Web browsers (Internet Explorer, Opera, Firefox) Mail Clients (Thunderbird, KMail, MS Outlook)
  • 6. TCP/IP, UDP sockets • An Internet socket is composed of • Protocol (TCP, UDP, raw IP) • Local IP address • Local port • Remote IP address • Remote port
  • 7. Unix Domain Socket • A Unix domain socket (UDS) or IPC socket • inter-process communication socket • a virtual socket • similar to an internet socket • used in POSIX operating systems for inter- process communication • connections appear as byte streams, much like network connections, • all data remains within the local computer
  • 8. IO::Socket • IO::Socket - Object interface to socket communications • built upon the IO::Handle interface and inherits all its methods • only defines methods for operations common to all types of socket • Operations, specified to a socket in a particular domain have methods defined in sub classes • will export all functions (and constants) defined by Socket
  • 9. IO::Socket • IO::Socket – Example (TCP/IP) #io-socket-tcp-client.pl use IO::Socket; my $sock = IO::Socket::INET->new( PeerAddr => $host, PeerPort => "$port", Proto => 'tcp', Timeout => 60 ) or die $@; die "Could not connect to $host$/" unless $sock->connected; #...
  • 10. IO::Socket • IO::Socket – Example 2 (TCP/IP) #io-socket-tcp-server.pl use IO::Socket; my ($host, $port, $path ) = ( 'localhost', 8088 ); my $server = new IO::Socket::INET ( LocalAddr => $host, LocalPort => $port, Proto => 'tcp', Listen => 10, Type => SOCK_STREAM, ReuseAddr => 1 ); print "Server ($0) running on port $port...n"; while (my $connection = $server->accept) { #...
  • 11. IO::Socket • IO::Socket – Example (UDS) #io-socket-uds-server.pl use IO::Socket; my $file = "./udssock"; unlink $file; my $server = IO::Socket::UNIX->new( Local => $file, Type => SOCK_STREAM, Listen => 5 ) or die $@; print "Server running on file $file...n"; #...
  • 12. IO::Socket • IO::Socket – Example 2 (UDS) #io-socket-uds-client.pl use IO::Socket; my $server = IO::Socket::UNIX->new( Peer => "./udssock", ) or die $@; # communicate with the server print "Client connected.n"; print "Server says: ", $server->getline; $server->print("Hello from the client!n"); $server->print("And goodbye!n"); $server->close; #...
  • 13. IO::Socket • IO::Socket – Example (UDP) #io-socket-udp-server.pl use IO::Socket; my $port = 4444; my $server = new IO::Socket::INET( LocalPort => $port, Proto => 'udp', ); die "Bind failed: $!n" unless $server; print "Server running on port $port...n"; #...
  • 14. IO::Socket • IO::Socket – Example 2 (UDP) #io-socket-udp-client.pl use IO::Socket; my $host = 'localhost'; my $port = 4444; my $client = new IO::Socket::INET( PeerAddr => $host, PeerPort => $port, Timeout => 2, Proto => 'udp', ); $client->send("Hello from client") or die "Send: $!n"; my $message; $client->recv($message, 1024, 0); print "Response was: $messagen"; #...
  • 15. HTTP and SMTP • HTTP • SMTP
  • 16. Sending Mail • Net::SMTP #smtp.pl use Net::SMTP; my $smtp = Net::SMTP->new( Host => 'localhost', Timeout => 30, Hello =>'localhost', ); my $from = 'me@example.com'; my @to = ('you@example.org',); my $text = $ARGV[0]|| 'проба'; my $mess = "ERROR: Can't send mail using Net::SMTP. "; $smtp->mail( $from ) || die $mess; $smtp->to( @to, { SkipBad => 1 } ) || die $mess; $smtp->data( $text ) || die $mess; $smtp->dataend() || die $mess; $smtp->quit();
  • 17. LWP and WWW::Mechanize • LWP - The World-Wide Web library for Perl • provides a simple and consistent application programming interface (API) to the World-Wide Web • classes and functions that allow you to write WWW clients • also contains modules that help you implement simple HTTP servers • supports access to http, https, gopher, ftp, news, file, and mailto resources • transparent redirect, parser for robots.txt files etc...
  • 18. LWP and WWW::Mechanize • WWW::Mechanize - Handy web browsing in a Perl object • helps you automate interaction with a website • well suited for use in testing web applications • is a proper subclass of LWP::UserAgent • you can also use any of the LWP::UserAgent's methods.
  • 19. LWP and WWW::Mechanize • WWW::Mechanize - Example • helps you automate interaction with a website • well suited for use in testing web applications • is a proper subclass of LWP::UserAgent • you can also use any of the LWP::UserAgent's methods.
  • 20. LWP and WWW::Mechanize • Example – getting product data from a site #www_mech.pl use strict; use warnings; use MyMech; use Data::Dumper; #Config $MyMech::Config->{DEBUG}=0; my $Config = $MyMech::Config; #print Dumper($Config); my $mech = MyMech->new( agent => $Config->{agent}, cookie_jar => $Config->{cookie_jar}, autocheck => $Config->{autocheck}, onwarn => $Config->{onwarn} ); #...
  • 21. Network programming • Resources • Beginning Perl (Chapter 14 – The World of Perl/IPC and Networking) • Professional Perl Programming (Chapter 23 – Networking with Perl) • perldoc perlipc • perldoc IO::Socket • http://en.wikipedia.org/wiki/Berkeley_sockets • Perl & LWP (http://lwp.interglacial.com/)