SlideShare una empresa de Scribd logo
1 de 34
Descargar para leer sin conexión
Java Networking


                  1
Topics
●   Basic Concepts on Networking
    –   IP Address
    –   Protocol
    –   Ports
    –   The Client/Server Paradigm
    –   Sockets


●   The Java Networking Package
    –   The ServerSocket and the Socket Class
    –   The MulticastSocket and the DatagramPacket Class
                                                           2
Basic Concepts on Networking
●   The Internet
    –   A global network of computers connected together in
        various ways
    –   Remains functional despite of diversity of hardware
        and software connected together
         ●   Possible through communication standards defined
             and conformed to
         ●   Guarantee compatibility and reliability of
             communication



                                                                3
Basic Concepts on Networking: IP
               Address
●   Logically similar to the traditional mailing address
     –   An address uniquely identifies a particular object


●   Each computer connected to the Internet has a
    unique IP address

●   A 32-bit number used to uniquely identify each
    computer connected to the Internet
     –   192.1.1.1
     –   docs.rinet.ru
                                                              4
Basic Concepts on Networking:
               Protocol
●   Why protocols?
    –   Different types of communication occurring over the
        Internet
    –   Each type of communication requires a specific and
        unique protocol


●   Definition
    –   Set of rules and standards that define a certain type
        of Internet communication
    –   Describes the following information:
         ●   Format of data being sent over the Internet        5
Basic Concepts on Networking:
              Protocol
●   Not entirely new to us. Consider this type of
    conversation:
         "Hello."
         "Hello. Good afternoon. May I please speak at Joan?"
         "Okay, please wait for a while."
         "Thanks."
         ...
    –   Social protocol used in a telephone conversation
    –   Gives us confidence and familiarity of knowing what
        to do

                                                                6
Basic Concepts on Networking:
              Protocol
●   Some important protocols used over the Internet
    –   Hypertext Transfer Protocol (HTTP)
         ●   Used to transfer HTML documents on the Web
    –   File Transfer Protocol (FTP)
         ●   More general compared to HTTP
         ●   Allows you to transfer binary files over the Internet
    –   Both protocols have their own set of rules and
        standards on how data is transferred
    –   Java provides support for both protocols


                                                                     7
Basic Concepts on Networking: Ports
●   Protocols only make sense when used in the
    context of a service
    –   HTTP protocol is used when you are providing Web
        content through an HTTP service
    –   Each computer on the Internet can provide a variety
        of services


●   Why Ports?
    –   The type of service must be known before
        information can be transferred

                                                              8
Basic Concepts on Networking: Ports
●   Definition:
    –   A 16-bit number that identifies each service offered
        by a network server

●   Using a particular service to establish a line of
    communication through a specific protocol
    –   Need to connect to the appropriate port




                                                               9
Basic Concepts on Networking: Ports
●   Standard ports
    –   Numbers specifically associated with a particular
        type of service
    –   Examples:
         ●   The FTP service is located on port 21
         ●   The HTTP service is located on port 80
    –   Given port values below 1024


●   Port values above 1024
    –   Available for custom communication
                                                            10
Basic Concepts on Networking: The
      Client/Server Paradigm
●   Basis for Java networking framework

●   Involves two major elements:
    –   Client
         ●   Machine in need of some type of information
    –   Server
         ●   Machine storing information and waiting to give it out


●   Scenario:
    –   Client connects to a server and queries for certain
                                                                      11
Basic Concepts on Networking: The
      Client/Server Paradigm




                                12
Basic Concepts on Networking:
               Sockets
●   Definitions:
    –   Software abstraction for an input or output medium
        of communication
    –   Communication channels that enable you to transfer
        data through a particular port
    –   An endpoint for communication between two
        machines
    –   A particular type of network communication used in
        most Java network programming
    –   Java performs all of its low-level network
        communication through sockets
                                                             13
The Java Networking Package
●   The java.net package

●   Provides classes useful for developing networking
    applications

●   Some classes in the package:
    –   ServerSocket
    –   Socket
    –   MulticastSocket
    –   DatagramPacket
                                                        14
The ServerSocket Class
●   Provides the basic functionalities of a server

●   Has four constructors




                                                     15
The ServerSocket Class: Methods




                                  16
The ServerSocket Class: Example
1    import java.net.*;
2    import java.io.*;
3    public class EchoingServer {
4       public static void main(String [] args) {
5          ServerSocket server = null;
6          Socket client;
7          try {
8              server = new ServerSocket(1234);
9              //1234 is an unused port number
10         } catch (IOException ie) {
11             System.out.println("Cannot open socket.");
12             System.exit(1);
13         }
14   //continued...
                                                            17
The ServerSocket Class: Example
15       while(true) {
16         try {
17            client = server.accept();
18            OutputStream clientOut =
19                       client.getOutputStream();
20            PrintWriter pw =
21                       new PrintWriter(clientOut, true);
22            InputStream clientIn =
23                       client.getInputStream();
24            BufferedReader br = new BufferedReader(new
25                           InputStreamReader(clientIn));
26            pw.println(br.readLine());
27         } catch (IOException ie) {}}}
28   }
                                                           18
The Socket Class
●   Implements a client socket

●   Has eight constructors
    –   Two of which are already deprecated




                                              19
The Socket Class: Methods




                            20
The Socket Class: Example
1    import java.io.*;
2    import java.net.*;
3

4    public class MyClient {
5       public static void main(String args[]) {
6         try {
7            /* Socket client = new Socket("133.0.0.1",
8                                              1234); */
9            Socket client =
10                    new Socket(InetAddress.getLocalHost(),
11                              1234);
12   //continued...


                                                               21
The Socket Class: Example
13           InputStream clientIn =
14                       client.getInputStream();
15           OutputStream clientOut =
16                       client.getOutputStream();
17           PrintWriter pw = new PrintWriter(clientOut,
18                                            true);
19           BufferedReader br = new BufferedReader(new
20                          InputStreamReader(clientIn));
21           BufferedReader stdIn = new BufferedReader(new
22                          InputStreamReader(System.in));
23           System.out.println("Type a message for
24                               the server: ");
25   //continued...
                                                             22
The Socket Class: Example
26               pw.println(stdIn.readLine());
27               System.out.println("Server message: ");
28               System.out.println(br.readLine());
29               pw.close();
30               br.close();
31               client.close();
32           } catch (ConnectException ce) {
33               System.out.println("Cannot connect to
34                                  the server.");
35           } catch (IOException ie) {
36               System.out.println("I/O Error.");
37           }
38       }
39   }                                                     23
The MulticastSocket Class
●   Useful for applications that implement group
    communication

●   IP addresses for a multicast group lies within the
    range 224.0.0.0 to 239.255.255.255
    –   Address 224.0.0.0 is reserved and should not be
        used

●   Has three constructors


                                                          24
The MulticastSocket Class: Methods




                                 25
The MulticastSocket Class
●   Sending a message to a group
    –   Should be a member of the multicast group by using
        the joinGroup method
    –   Use the send method
    –   Once done, can use the leaveGroup method


●   The send method
    –   Need to pass a DatagramPacket object



                                                             26
The DatagramPacket Class
●   Used to deliver data through a connectionless
    protocol

●   Problem: delivery of packets is not guaranteed

●   Has six constructors




                                                     27
The DatagramPacket Class: Methods




                                28
The MulticastSocket Class: Server
                 Example
1    import java.net.*;
2    public class ChatServer {
3       public static void main(String args[])
4                                throws Exception {
5          MulticastSocket server =
6                      new MulticastSocket(1234);
7          InetAddress group =
8                      InetAddress.getByName("234.5.6.7");
9          //getByName- returns IP address of given host
10         server.joinGroup(group);
11         boolean infinite = true;
12   //continued
                                                             29
The MulticastSocket Class: Server
                 Example
13           /* Continually receives data and prints them */
14           while(infinite) {
15               byte buf[] = new byte[1024];
16               DatagramPacket data =
17                      new DatagramPacket(buf, buf.length);
18               server.receive(data);
19               String msg =
20                      new String(data.getData()).trim();
21               System.out.println(msg);
22           }
23           server.close();
24       }
25   }                                                         30
The MulticastSocket Class: Client
                 Example
1    import java.net.*;
2    import java.io.*;
3    public class ChatClient {
4       public static void main(String args[])
5                                throws Exception {
6          MulticastSocket chat = new MulticastSocket(1234);
7          InetAddress group =
8                         InetAddress.getByName("234.5.6.7");
9          chat.joinGroup(group);
10         String msg = "";
11   //continued...


                                                            31
The MulticastSocket Class: Client
                 Example
12           System.out.println("Type a message for
13                                  the server:");
14           BufferedReader br = new BufferedReader(new
15                           InputStreamReader(System.in));
16           msg = br.readLine();
17           DatagramPacket data = new
18                       DatagramPacket(msg.getBytes(), 0,
19                                  msg.length(), group, 1234);
20           chat.send(data);
21           chat.close();
22       }
23   }
                                                                  32
Summary
●   Basic Concepts on Networking
    –   IP Address
    –   Protocol
    –   Ports
    –   The Client/Server Paradigm
    –   Sockets




                                     33
Summary
●   The Java Networking Package
    –   ServerSocket
    –   Socket
    –   MulticastSocket
    –   DatagramPacket




                                  34

Más contenido relacionado

La actualidad más candente

La actualidad más candente (20)

OpenStack Networking
OpenStack NetworkingOpenStack Networking
OpenStack Networking
 
Running BGP with Mikrotik
Running BGP with MikrotikRunning BGP with Mikrotik
Running BGP with Mikrotik
 
Socket Programming with Python
Socket Programming with PythonSocket Programming with Python
Socket Programming with Python
 
Openstack Networking and ML2
Openstack Networking and ML2Openstack Networking and ML2
Openstack Networking and ML2
 
Python lecture 11
Python lecture 11Python lecture 11
Python lecture 11
 
Internet Protocol Deep-Dive
Internet Protocol Deep-DiveInternet Protocol Deep-Dive
Internet Protocol Deep-Dive
 
EOIP Deep Dive
EOIP Deep DiveEOIP Deep Dive
EOIP Deep Dive
 
Mikrotik IP Settings For Performance and Security
Mikrotik IP Settings For Performance and SecurityMikrotik IP Settings For Performance and Security
Mikrotik IP Settings For Performance and Security
 
BGP on RouterOS7 -Part 1
BGP on RouterOS7 -Part 1BGP on RouterOS7 -Part 1
BGP on RouterOS7 -Part 1
 
Automatic Backup via FTP - Part 1
Automatic Backup via FTP - Part 1Automatic Backup via FTP - Part 1
Automatic Backup via FTP - Part 1
 
MTCNA : Intro to RouterOS - Part 1
MTCNA : Intro to RouterOS - Part 1MTCNA : Intro to RouterOS - Part 1
MTCNA : Intro to RouterOS - Part 1
 
Introduction to MQTT
Introduction to MQTTIntroduction to MQTT
Introduction to MQTT
 
Troubleshooting Layer 2 Ethernet Problem: Loop, Broadcast, Security
Troubleshooting Layer 2 Ethernet Problem: Loop, Broadcast, Security Troubleshooting Layer 2 Ethernet Problem: Loop, Broadcast, Security
Troubleshooting Layer 2 Ethernet Problem: Loop, Broadcast, Security
 
Twisted
TwistedTwisted
Twisted
 
Using Mikrotik Switch Features to Improve Your Network
Using Mikrotik Switch Features to Improve Your Network Using Mikrotik Switch Features to Improve Your Network
Using Mikrotik Switch Features to Improve Your Network
 
Zabbix for Monitoring
Zabbix for MonitoringZabbix for Monitoring
Zabbix for Monitoring
 
Voice Services, From Circuit Switch to VoIP
Voice Services, From Circuit Switch to VoIPVoice Services, From Circuit Switch to VoIP
Voice Services, From Circuit Switch to VoIP
 
ACL on Linux - Part 1
ACL on Linux - Part 1ACL on Linux - Part 1
ACL on Linux - Part 1
 
OpenStack Neutron new developers on boarding
OpenStack Neutron new developers on boardingOpenStack Neutron new developers on boarding
OpenStack Neutron new developers on boarding
 
Provide Internet Services Using GPON
Provide Internet Services Using GPONProvide Internet Services Using GPON
Provide Internet Services Using GPON
 

Destacado (9)

Open Distributed Networking Intelligence: A New Java Paradigm
Open Distributed Networking Intelligence: A New Java ParadigmOpen Distributed Networking Intelligence: A New Java Paradigm
Open Distributed Networking Intelligence: A New Java Paradigm
 
JDBC
JDBCJDBC
JDBC
 
North Port, Malaysia
North Port, MalaysiaNorth Port, Malaysia
North Port, Malaysia
 
Different types of ports
Different types of portsDifferent types of ports
Different types of ports
 
Ebola, ethical issues
Ebola, ethical issuesEbola, ethical issues
Ebola, ethical issues
 
Dry port logistics 2015
Dry port logistics 2015 Dry port logistics 2015
Dry port logistics 2015
 
Java Networking
Java NetworkingJava Networking
Java Networking
 
java networking
 java networking java networking
java networking
 
Network programming in java - PPT
Network programming in java - PPTNetwork programming in java - PPT
Network programming in java - PPT
 

Similar a javanetworking

04 android
04 android04 android
04 android
guru472
 
chapter-4-networking hjgjjgj did hfhhfhj
chapter-4-networking hjgjjgj did hfhhfhjchapter-4-networking hjgjjgj did hfhhfhj
chapter-4-networking hjgjjgj did hfhhfhj
AmitDeshai
 
15network Programming Clients
15network Programming Clients15network Programming Clients
15network Programming Clients
Adil Jafri
 

Similar a javanetworking (20)

Network-Connected Development with ZeroMQ
Network-Connected Development with ZeroMQNetwork-Connected Development with ZeroMQ
Network-Connected Development with ZeroMQ
 
04 android
04 android04 android
04 android
 
A.java
A.javaA.java
A.java
 
Mina2
Mina2Mina2
Mina2
 
28 networking
28  networking28  networking
28 networking
 
5_6278455688045789623.pptx
5_6278455688045789623.pptx5_6278455688045789623.pptx
5_6278455688045789623.pptx
 
Byte Ordering - Unit 2.pptx
Byte Ordering - Unit 2.pptxByte Ordering - Unit 2.pptx
Byte Ordering - Unit 2.pptx
 
IPv6 with Mikrotik
IPv6 with MikrotikIPv6 with Mikrotik
IPv6 with Mikrotik
 
chapter-4-networking hjgjjgj did hfhhfhj
chapter-4-networking hjgjjgj did hfhhfhjchapter-4-networking hjgjjgj did hfhhfhj
chapter-4-networking hjgjjgj did hfhhfhj
 
PuppetConf 2016: Why Network Automation Matters, and What You Can Do About It...
PuppetConf 2016: Why Network Automation Matters, and What You Can Do About It...PuppetConf 2016: Why Network Automation Matters, and What You Can Do About It...
PuppetConf 2016: Why Network Automation Matters, and What You Can Do About It...
 
Building the Internet of Things with Thingsquare and Contiki - day 1, part 3
Building the Internet of Things with Thingsquare and Contiki - day 1, part 3Building the Internet of Things with Thingsquare and Contiki - day 1, part 3
Building the Internet of Things with Thingsquare and Contiki - day 1, part 3
 
Socket programming using C
Socket programming using CSocket programming using C
Socket programming using C
 
Publishing Microservices Applications
Publishing Microservices ApplicationsPublishing Microservices Applications
Publishing Microservices Applications
 
Java socket programming
Java socket programmingJava socket programming
Java socket programming
 
Netty Cookbook - Chapter 2
Netty Cookbook - Chapter 2Netty Cookbook - Chapter 2
Netty Cookbook - Chapter 2
 
Matrix.org decentralised communication, Matthew Hodgson, TADSummit
Matrix.org decentralised communication, Matthew Hodgson, TADSummitMatrix.org decentralised communication, Matthew Hodgson, TADSummit
Matrix.org decentralised communication, Matthew Hodgson, TADSummit
 
[Call for code] IBM 블록체인을 활용하여 투명하게 구호기금 관리하기 - Hyperledger Fabric v1.1 by 맹개발
[Call for code] IBM 블록체인을 활용하여 투명하게 구호기금 관리하기 - Hyperledger Fabric v1.1 by 맹개발 [Call for code] IBM 블록체인을 활용하여 투명하게 구호기금 관리하기 - Hyperledger Fabric v1.1 by 맹개발
[Call for code] IBM 블록체인을 활용하여 투명하게 구호기금 관리하기 - Hyperledger Fabric v1.1 by 맹개발
 
Networking in java, Advanced programming
Networking in java, Advanced programmingNetworking in java, Advanced programming
Networking in java, Advanced programming
 
Chap 1 Network Theory & Java Overview
Chap 1   Network Theory & Java OverviewChap 1   Network Theory & Java Overview
Chap 1 Network Theory & Java Overview
 
15network Programming Clients
15network Programming Clients15network Programming Clients
15network Programming Clients
 

Más de Arjun Shanka (20)

Asp.net w3schools
Asp.net w3schoolsAsp.net w3schools
Asp.net w3schools
 
Php tutorial(w3schools)
Php tutorial(w3schools)Php tutorial(w3schools)
Php tutorial(w3schools)
 
Sms several papers
Sms several papersSms several papers
Sms several papers
 
Jun 2012(1)
Jun 2012(1)Jun 2012(1)
Jun 2012(1)
 
System simulation 06_cs82
System simulation 06_cs82System simulation 06_cs82
System simulation 06_cs82
 
javaexceptions
javaexceptionsjavaexceptions
javaexceptions
 
javainheritance
javainheritancejavainheritance
javainheritance
 
javarmi
javarmijavarmi
javarmi
 
java-06inheritance
java-06inheritancejava-06inheritance
java-06inheritance
 
hibernate
hibernatehibernate
hibernate
 
javapackage
javapackagejavapackage
javapackage
 
javaarray
javaarrayjavaarray
javaarray
 
swingbasics
swingbasicsswingbasics
swingbasics
 
spring-tutorial
spring-tutorialspring-tutorial
spring-tutorial
 
struts
strutsstruts
struts
 
javathreads
javathreadsjavathreads
javathreads
 
javabeans
javabeansjavabeans
javabeans
 
72185-26528-StrutsMVC
72185-26528-StrutsMVC72185-26528-StrutsMVC
72185-26528-StrutsMVC
 
javaiostream
javaiostreamjavaiostream
javaiostream
 
servlets
servletsservlets
servlets
 

Último

Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Victor Rentea
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Victor Rentea
 

Último (20)

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
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
 
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...
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)
 
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
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 
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
 
"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 ...
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 

javanetworking

  • 2. Topics ● Basic Concepts on Networking – IP Address – Protocol – Ports – The Client/Server Paradigm – Sockets ● The Java Networking Package – The ServerSocket and the Socket Class – The MulticastSocket and the DatagramPacket Class 2
  • 3. Basic Concepts on Networking ● The Internet – A global network of computers connected together in various ways – Remains functional despite of diversity of hardware and software connected together ● Possible through communication standards defined and conformed to ● Guarantee compatibility and reliability of communication 3
  • 4. Basic Concepts on Networking: IP Address ● Logically similar to the traditional mailing address – An address uniquely identifies a particular object ● Each computer connected to the Internet has a unique IP address ● A 32-bit number used to uniquely identify each computer connected to the Internet – 192.1.1.1 – docs.rinet.ru 4
  • 5. Basic Concepts on Networking: Protocol ● Why protocols? – Different types of communication occurring over the Internet – Each type of communication requires a specific and unique protocol ● Definition – Set of rules and standards that define a certain type of Internet communication – Describes the following information: ● Format of data being sent over the Internet 5
  • 6. Basic Concepts on Networking: Protocol ● Not entirely new to us. Consider this type of conversation: "Hello." "Hello. Good afternoon. May I please speak at Joan?" "Okay, please wait for a while." "Thanks." ... – Social protocol used in a telephone conversation – Gives us confidence and familiarity of knowing what to do 6
  • 7. Basic Concepts on Networking: Protocol ● Some important protocols used over the Internet – Hypertext Transfer Protocol (HTTP) ● Used to transfer HTML documents on the Web – File Transfer Protocol (FTP) ● More general compared to HTTP ● Allows you to transfer binary files over the Internet – Both protocols have their own set of rules and standards on how data is transferred – Java provides support for both protocols 7
  • 8. Basic Concepts on Networking: Ports ● Protocols only make sense when used in the context of a service – HTTP protocol is used when you are providing Web content through an HTTP service – Each computer on the Internet can provide a variety of services ● Why Ports? – The type of service must be known before information can be transferred 8
  • 9. Basic Concepts on Networking: Ports ● Definition: – A 16-bit number that identifies each service offered by a network server ● Using a particular service to establish a line of communication through a specific protocol – Need to connect to the appropriate port 9
  • 10. Basic Concepts on Networking: Ports ● Standard ports – Numbers specifically associated with a particular type of service – Examples: ● The FTP service is located on port 21 ● The HTTP service is located on port 80 – Given port values below 1024 ● Port values above 1024 – Available for custom communication 10
  • 11. Basic Concepts on Networking: The Client/Server Paradigm ● Basis for Java networking framework ● Involves two major elements: – Client ● Machine in need of some type of information – Server ● Machine storing information and waiting to give it out ● Scenario: – Client connects to a server and queries for certain 11
  • 12. Basic Concepts on Networking: The Client/Server Paradigm 12
  • 13. Basic Concepts on Networking: Sockets ● Definitions: – Software abstraction for an input or output medium of communication – Communication channels that enable you to transfer data through a particular port – An endpoint for communication between two machines – A particular type of network communication used in most Java network programming – Java performs all of its low-level network communication through sockets 13
  • 14. The Java Networking Package ● The java.net package ● Provides classes useful for developing networking applications ● Some classes in the package: – ServerSocket – Socket – MulticastSocket – DatagramPacket 14
  • 15. The ServerSocket Class ● Provides the basic functionalities of a server ● Has four constructors 15
  • 17. The ServerSocket Class: Example 1 import java.net.*; 2 import java.io.*; 3 public class EchoingServer { 4 public static void main(String [] args) { 5 ServerSocket server = null; 6 Socket client; 7 try { 8 server = new ServerSocket(1234); 9 //1234 is an unused port number 10 } catch (IOException ie) { 11 System.out.println("Cannot open socket."); 12 System.exit(1); 13 } 14 //continued... 17
  • 18. The ServerSocket Class: Example 15 while(true) { 16 try { 17 client = server.accept(); 18 OutputStream clientOut = 19 client.getOutputStream(); 20 PrintWriter pw = 21 new PrintWriter(clientOut, true); 22 InputStream clientIn = 23 client.getInputStream(); 24 BufferedReader br = new BufferedReader(new 25 InputStreamReader(clientIn)); 26 pw.println(br.readLine()); 27 } catch (IOException ie) {}}} 28 } 18
  • 19. The Socket Class ● Implements a client socket ● Has eight constructors – Two of which are already deprecated 19
  • 20. The Socket Class: Methods 20
  • 21. The Socket Class: Example 1 import java.io.*; 2 import java.net.*; 3 4 public class MyClient { 5 public static void main(String args[]) { 6 try { 7 /* Socket client = new Socket("133.0.0.1", 8 1234); */ 9 Socket client = 10 new Socket(InetAddress.getLocalHost(), 11 1234); 12 //continued... 21
  • 22. The Socket Class: Example 13 InputStream clientIn = 14 client.getInputStream(); 15 OutputStream clientOut = 16 client.getOutputStream(); 17 PrintWriter pw = new PrintWriter(clientOut, 18 true); 19 BufferedReader br = new BufferedReader(new 20 InputStreamReader(clientIn)); 21 BufferedReader stdIn = new BufferedReader(new 22 InputStreamReader(System.in)); 23 System.out.println("Type a message for 24 the server: "); 25 //continued... 22
  • 23. The Socket Class: Example 26 pw.println(stdIn.readLine()); 27 System.out.println("Server message: "); 28 System.out.println(br.readLine()); 29 pw.close(); 30 br.close(); 31 client.close(); 32 } catch (ConnectException ce) { 33 System.out.println("Cannot connect to 34 the server."); 35 } catch (IOException ie) { 36 System.out.println("I/O Error."); 37 } 38 } 39 } 23
  • 24. The MulticastSocket Class ● Useful for applications that implement group communication ● IP addresses for a multicast group lies within the range 224.0.0.0 to 239.255.255.255 – Address 224.0.0.0 is reserved and should not be used ● Has three constructors 24
  • 26. The MulticastSocket Class ● Sending a message to a group – Should be a member of the multicast group by using the joinGroup method – Use the send method – Once done, can use the leaveGroup method ● The send method – Need to pass a DatagramPacket object 26
  • 27. The DatagramPacket Class ● Used to deliver data through a connectionless protocol ● Problem: delivery of packets is not guaranteed ● Has six constructors 27
  • 29. The MulticastSocket Class: Server Example 1 import java.net.*; 2 public class ChatServer { 3 public static void main(String args[]) 4 throws Exception { 5 MulticastSocket server = 6 new MulticastSocket(1234); 7 InetAddress group = 8 InetAddress.getByName("234.5.6.7"); 9 //getByName- returns IP address of given host 10 server.joinGroup(group); 11 boolean infinite = true; 12 //continued 29
  • 30. The MulticastSocket Class: Server Example 13 /* Continually receives data and prints them */ 14 while(infinite) { 15 byte buf[] = new byte[1024]; 16 DatagramPacket data = 17 new DatagramPacket(buf, buf.length); 18 server.receive(data); 19 String msg = 20 new String(data.getData()).trim(); 21 System.out.println(msg); 22 } 23 server.close(); 24 } 25 } 30
  • 31. The MulticastSocket Class: Client Example 1 import java.net.*; 2 import java.io.*; 3 public class ChatClient { 4 public static void main(String args[]) 5 throws Exception { 6 MulticastSocket chat = new MulticastSocket(1234); 7 InetAddress group = 8 InetAddress.getByName("234.5.6.7"); 9 chat.joinGroup(group); 10 String msg = ""; 11 //continued... 31
  • 32. The MulticastSocket Class: Client Example 12 System.out.println("Type a message for 13 the server:"); 14 BufferedReader br = new BufferedReader(new 15 InputStreamReader(System.in)); 16 msg = br.readLine(); 17 DatagramPacket data = new 18 DatagramPacket(msg.getBytes(), 0, 19 msg.length(), group, 1234); 20 chat.send(data); 21 chat.close(); 22 } 23 } 32
  • 33. Summary ● Basic Concepts on Networking – IP Address – Protocol – Ports – The Client/Server Paradigm – Sockets 33
  • 34. Summary ● The Java Networking Package – ServerSocket – Socket – MulticastSocket – DatagramPacket 34