CHAPTER 5
Java Programming for Networking Applications

“Nothing is so embarrassing as watching someone do something that you said couldn't be done.”

—Sam Ewing

5.1 Introduction

Computer networks have become an increasingly integrated part of our lives. With the Internet, the fast-growing, globalized computer network of networks, we are able to do shopping, banking, emailing, messaging, and booking flights or hotels online, all with just a few mouse clicks. The Internet has revolutionized our lives. According to the Internet Live Stats web site (http://www.internetlivestats.com/internet-users/), there are more than 4 billion Internet users today.

The magic behind this Internet phenomenon is a technology known as TCP/IP, which was developed through the U.S. Advanced Research Projects Agency (ARPA)'s research project ARPANET in the 1960s. ARPA is a research arm of the United States Department of Defense, so TCP/IP has also been called the Department of Defense (DoD) model.

The TCP/IP model consists of a whole suite of protocols, built around two core protocols: Transmission Control Protocol (TCP) and Internet Protocol (IP). IP defines a scheme of devices addresses and delivers data from device to device based on those IP addresses, and TCP provides the control of the delivery. The TCP/IP model is divided into four layers: Application, Transport, Internet, and Link (see Figure 5.1).

Schematic diagram depicting Application, Transport, Internet, and Link layers of TCP/IP model with protocols at the right connected by lines.

Figure 5.1: The TCP/IP model and its protocols

  • The Application layer provides an interface between users or user programs and the underneath communication protocols. The main protocols in this layer are Hypertext Transfer Protocol/ Hypertext Transfer Protocol Secure (HTTP/HTTPS) for web services, File Transfer Protocol (FTP) for file upload/download, Simple Mail Transfer Protocol (SMTP) for emails, Post Office Protocol (POP3) for retrieving email from an email server, Secure Shell (SSH) for remote login, Domain Name System (DNS) for translating domains to IP addresses and vice versa, and Dynamic Host Configuration Protocol (DHCP) for automatic host configuration.
  • The Transport layer manages the data transmission and provides services such as connection-oriented communication, reliability, flow control, and multiplexing. The main protocols in this layer are TCP for reliable transmission and User Datagram Protocol (UDP) for real-time transmission.
  • The Internet layer delivers the data, called packets, from source device to destination device, based on IP addresses. The main protocol in this layer is IP for delivering data. Also in the layer are Internet Control Message Protocol (ICMP) for error reporting and Internet Group Management Protocol (IGMP) for multicast.
  • The Link layer deals with the physical components of the networking devices, such as Ethernet, Token Ring, Fiber Optics, and WiFi connections. It is sometimes referred to as the Network Interface layer. The Link layer can also be subdivided into a Data Link layer and Physical layer. The main protocols in this layer are Address Resolution Protocol (ARP) for resolving IP addresses into hardware addresses or Medium Access Control (MAC) addresses, Reverse Address Resolution Protocol (RARP), and Neighbor Discovery Protocol (NDP) for gathering information about neighbor devices.

Any computers, phones, tablets, or other devices on the Internet must have TCP/IP suite software installed to function, as shown in Figure 5.2. Each device also needs its own IP address and port number to communicate with other devices on the network. The IP address is used to uniquely identify the device, a bit like a telephone number. There are two types of IP addresses: IP version 4 (IPv4) and IP version 6 (IPv6). IPv4 addresses are 32-bit binary addresses that are commonly expressed in dotted decimal format, such as 10.0.0.1, 136.148.1.27, or 192.168.0.1. IPv6 addresses are the new 128-bit binary addresses that are commonly expressed in hexadecimal format separated by colons, such as FE80:CD00:0000:0CDE:1257:0000:211E:729C, 2001:0DB8:85A3:0000:0000:8A2E:0370:7334, or FF01:0:0:0:0:0:0:1. The four billion IPv4 addresses have already been exhausted, so IPv6 addressing is going to be the future. There are 3.4×1038 IPv6 addresses in total, enough to assign an address to every single grain of sand on Earth. The port number is used to uniquely identify the programs you run on your device, such as web browsers, email agents, and chat programs. The port number is a 16-bit binary number, ranging from 0 to 65535. The port numbers 0–1023 are well-known port numbers, also called system ports. Here are some examples:

Schematic diagram depicting TCP/IP model, Servers; IP address, Computers; and port number, Mobile Devices exchanged over the Internet.

Figure 5.2: The TCP/IP model, IP address, and port number exchanged over the Internet

20: FTP (data transfer)

21: FTP (command control)

22: SSH

25: SMTP

53: DNS

67: DHCP Server

68: DHCP Client

80: HTTP

110: POP3

443: HTTPS

The port numbers 1024–49151 are called registered ports. The port numbers 49152–65535 are called ephemeral ports. When you are writing your Java programs, you should not use system ports; instead, you should use the registered ports or ephemeral ports.

For more details about TCP/IP, please visit the following resources:

https://en.wikipedia.org/wiki/Internet_protocol_suite

http://www.pearsonitcertification.com/articles/article.aspx?p=1804869

https://docs.oracle.com/cd/E19683-01/806-4075/ipov-10/index.html

https://www.cisco.com/c/en/us/support/docs/ip/routing-information-protocol-rip/13769-5.html

5.1.1 Local Area Network and Wide Area Network

A computer network can be physically classified as either a local area network (LAN) or a wide area network (WAN). A LAN is a group of interconnected computers within a building or a campus. A WAN is a collection of LANs that are spread out over a large area. A WAN within a city is also called a metropolitan area network (MAN). A LAN typically belongs to one organization and has high-speed connections, such as Fast Ethernet (100 Mbps) or Gigabit Ethernet (1000 Mbps). A MAN or WAN typically belongs to different organizations and has relatively low-speed connections. The Internet is an example of a worldwide public WAN.

5.1.2 The Cisco Three-Tier Enterprise Network Architecture

Large organizations with huge computer networks typically adopt Cisco's three-tiered enterprise network architecture, shown in Figure 5.3. From top to bottom, the tiers are Core, Distribution, and Access.

Schematic diagram depicting Cisco three-tier enterprise network architecture with Core Layer, Gateway (top); Distribution Layer, routers (middle); Access Layer, Office 1 and 2 and Server components (bottom).

Figure 5.3: The Cisco three-tier enterprise network architecture

  • The Access layer provides the network access to end-user devices, such as computers, printers, or servers. The typical networking devices are switches, which connect all the devices in either a star network topology or a tree network topology (which consists of several star network topologies connected in a hierarchical structure).
  • The Distribution layer bridges the gap between the Access layer and the Core layer. The typical networking devices are routers, which connect all the switches in the Access layer to the Core layer. The Distribution layer also provides the network connection with redundancy by using mesh network topology.
  • The Core layer connects all the distribution routers together and provides the Internet access. The core layer is also known as the backbone. The typical networking device is a gateway router, also called the default gateway. Large organizations may have more than one gateway router to provide the Internet connection with more bandwidth and redundancy.

5.1.3 Key Network Components

Figure 5.3 shows the following key network components: switches, routers, a default gateway, and various servers such as DNS and DHCP servers. For a Windows computer network, you will also need a Windows Internet Name Service (WINS) server.

  • A switch is a device used to connect users’ client computers and usually has a large number of the same type of interface, called ports. A switch can have 8 ports, 16 ports, 64 ports, or even 128 ports.
  • A router is a device to connect different networks, not users’ computers, and usually has a few interfaces of different types, such as Ethernet, Fast Ethernet, Gigabit Ethernet, serial, Fiber Distributed Data Interface (FDDI), Asynchronous Transfer Mode (ATM), and Integrated Services Digital Network (ISDN). Routers are so called because they also perform routing functions to find the best route to a destination.
  • The gateway, or default gateway, is where the local computer network connects to the Internet. The gateway is also the place where the network proxy server, network policy, and network firewall are commonly implemented.
  • The DNS is another key component. The computers work based on IP addresses, but we humans are not good at remembering numbers, so we prefer names. DNS servers translate the human-understandable domain names into machine-understandable IP addresses, and vice versa.
  • The DHCP server automatically provides the network configuration information for your computer. The following are four minimum pieces of information you need to configure your computer to access the Internet:
    • IP address: To identify the device
    • Subnet mask: To identify the subnet of the device
    • DNS server: To know where the DNS server is
    • Default gateway: To know where the gateway router is

5.1.4 Traditional Networks vs. Software-Defined Networking

Traditionally, computer networks are composed of switches and routers. Each switch or router has two planes, a control plane, and a data plane (or forwarding plane), as shown on the left in Figure 5.4. The control plane determines where to send traffic data, and the data plane executes these decisions and forwards traffic data. In this scenario, you will need to configure each switch or router individually. This approach is therefore time-consuming and error-prone, which makes it difficult to cope with the scalability problems of growing computer networks.

Schematic diagrams depicting Traditional Network with two planes, a control plane, and a data plane and Software-Defined Network with control planes of switches and routers managed centrally using a dedicated server.

Figure 5.4: Comparing traditional and software-defined networks

Software-defined networking (SDN) is an emerging technology that has become a new key buzzword in the computer networking/IT industry. With SDN, the control planes of switches and routers are taken away from individual devices and managed centrally using a dedicated server, as shown on the right in Figure 5.4. SDN is a software layer that sits on the top of existing computer networks. The server controls the traffic centrally by programming the switches and routers directly. This brings several benefits.

  • Central management: You can configure, monitor, and troubleshoot the network all from the controller. You can also view the complete network topology from the controller.
  • Lighter-weight network devices: Because all the controls are performed centrally, you can use slimmed-down switches and routers to reduce network costs.
  • Network virtualization: SDN helps to virtualize the networks. Virtualization of networks has brought a revolution in the IT industry to virtualize storage and computing entities, which have played a key role in efficiently utilizing resources.

The most commonly used SDN communication protocol is OpenFlow, which is an open standard managed by the Open Networking Foundation. (You'll learn how to obtain and get started with it later in the chapter.) OpenFlow needs to be implemented in both switches/routers and the controller. OpenFlow carries messages between switches/routers and the controller. To control network switches/routers, the controller will use OpenFlow to push rules, such as forwarding rules and security rules, into switches/routers so that they can make decisions when network traffic hits them. Switches/routers need to maintain such rules in an OpenFlow table. Rules are also called flows and are stored in flow tables. To monitor switches/routers, the controller uses OpenFlow's various request and response messages to fetch the statistics information and events messages to update the controller about changes or failures that occur at switches/routers.

Floodlight is a popular SDN controller project. (You'll also learn how to obtain and get started with it later in the chapter.) It is a Java-based, Apache-licensed OpenFlow controller that you can use to help build a software-defined network. Floodlight is developed by an open community of developers, and it is simple to build and run. Floodlight supports a broad range of virtual and physical OpenFlow switches. Floodlight can handle mixed OpenFlow and non-OpenFlow networks. Floodlight is designed to be high-performance; it is multithreaded from the ground up, and it supports the OpenStack (link) cloud orchestration platform.

OpenDaylight is another Java-based open source SDN controller project. (You'll also learn how to obtain and get started with it later in the chapter.) It is a baseline project upon which many other controllers are built. The OpenDaylight project is conducted by the Linux Foundation. The goal of the project is to promote software-defined networking and network functions virtualization (NFV). NFV is another hot topic at the moment. SDN is closely related to NFV but is different. SDN focuses on separating the network's control plane from the forwarding plane and provides a centralized control of the network. NFV focuses on improving and virtualizing the network services themselves, such as DNS, caching, load balancing, firewalls, intrusion detection, and so on. Both SDN and NFV aim to advance a software-based approach to networking to make the network more scalable, more agile, and better supported.

In summary, SDN provides traffic programmability, agility, and the ability to create policy-driven network supervision and to implement network automation. It also allows the creation of a framework to support more data-intensive applications such as big data and virtualization. SDN can reduce both the capital expenses (CAPEX) of network equipment and the operational and maintenance expenses (OPEX) of a network. As a result, more and more companies are starting to adopt SDN.

For more details about SDN, please visit the following resources:

https://en.wikipedia.org/wiki/Software-defined_networking

https://en.wikipedia.org/wiki/OpenFlow

https://en.wikipedia.org/wiki/List_of_SDN_controller_software

https://www.cisco.com/c/en_uk/solutions/software-defined-networking/overview.html

https://www.juniper.net/uk/en/products-services/sdn/

https://github.com/mininet/openflow-tutorial/wiki

http://www.projectfloodlight.org/floodlight/

https://www.opendaylight.org/

http://sdnhub.org/tutorials/

5.2 Java Network Information Programming

Java, with its rich networking capabilities, is suitable for developing applications that run in networked and distributed computer environments. This chapter will focus on how to develop networking-based applications using Java.

With Java, you can easily write a program to get network information. Example 5.1 shows how to get the IP address and hostname of your computer using the inetAddress class. Figure 5.5 shows the compilation and execution of the program.

Screen capture depicting compilation and execution of the NetAddress.java program in Command Prompt.

Figure 5.5: The compilation and execution of the NetAddress.java program

Example 5.2 shows how to get the IP address and MAC address of your computer using the inetAddress and NetworkInterface classes. Figure 5.6 shows the compilation and execution of the program. The subnet 24 means 255.255.255.0.

Screen capture depicting compilation and execution of the NetInfo.java program in Command Prompt.

Figure 5.6: The compilation and execution of the NetInfo.java program

Example 5.3 shows a longer version of the network information program using the inetAddress and NetworkInterface classes. Figure 5.7 shows the compilation and execution of the program.

Screen capture depicting compilation and execution of the NetAddress2.java program in Command Prompt.

Figure 5.7: The compilation and execution of the Net Address2.java program

In Windows operating systems, ipconfig is a powerful command to get network information. You can run ipconfig to get a summary of your computer network information, and you can run ipconfig /all to get more detailed network information. Example 5.4 shows how to execute the ipconfig command in Java to get network information using system calls, as illustrated in Chapter 3. Figure 5.8 shows the compilation and execution of the program.

Screen capture depicting compilation and execution of the IPConfig1.java program in Command Prompt.

Figure 5.8: The compilation and execution of the IPConfig1.java program

Example 5.5 is an improved version of Example 5.4. This version searches for the DHCP server in the ipconfig /all command output using Java Pattern and Match classes. Java pattern matching is an efficient way of searching for a particular pattern within a given text. The following are the steps to use pattern matching:

Pattern pattern = Pattern.compile("DHCP Server");  //Create a pattern
Matcher matcher = pattern.matcher("");             //Create a text 
matcher.reset(line);                               //Reset the text 
matcher.find()                                     //Search the pattern                                                      in the text

Figure 5.9 shows the compilation and execution of the program.

Screen capture depicting compilation and execution of the IPConfig2.java program in Command Prompt.

Figure 5.9: The compilation and execution of the IPConfig2.java program

5.3 Java Socket Programming

In computer networks, a socket is an endpoint of a two-way communication channel between two computers over the Internet. A socket consists of an IP address and a port number. Java's Socket API supports two types of sockets: UDP sockets and TCP sockets. With a User Datagram Protocol socket, you can develop Java networking applications, such as audio or video chatting, which require simple, fast data transmission with minimum delays. With a Transport Control Protocol socket, you can develop Java networking applications, such as web, email, and file transfers, that require reliable data transmissions and have traffic flow control.

5.3.1 Java UDP Client-Server Programming

The User Datagram Protocol is a Transport layer protocol. UDP provides a connectionless, unreliable, but simple and fast service. Therefore, UDP is mostly used in time-critical applications such as Internet telephony, web broadcasts, or online video, where sending data without delay is more important than sending data without error.

Example 5.6 is a simple UDP client-server program. Example 5.6A, UDPServer1.java, is the server program, and Example 5.6B, UDPClient1.java, is the client program. In this example, the server program needs to run first, waiting for the client's connection, and the client program needs to run second so it can connect to server. In the client program, users need to type in a one-line sentence that will be sent to the server. When the server receives this data, it will echo it back to the client. Finally, the client will print out the server's response.

The following is the UDPServer1.java program's execution logic:

begin
    create a Server Datagram Socket on port 3301
    create a Datagram packet for receiving data
    receive data from a client
    print client's IP address and port number
    create another Datagram packet containing client's data
    send packet to client 
    close Socket
end

The following is the UDPClient1.java program's execution logic:

begin
    create a BufferReader associating with keyboard
    create a client Datagram Socket
    read in a line from keyboard
    create a Datagram packet containing that line
    send packet to server
    create another Datagram packet for receiving data from server
    receive data from server 
    print server's response
    close Socket
end

Figure 5.10 shows the compilation and execution of the UDPServer1.java program and the UDPClient1.java program. In this example, the server runs on localhost (127.0.0.1), port 3301; the client runs on localhost (127.0.0.1), port 3024. Please note that you will need two separate console windows to run the UDPServer1.java program and the UDPClient1.java program.

Screen capture depicting compilation and execution of the  UDPServer1.java (top) and UDPClient1.java (bottom) in Command Prompt.

Figure 5.10: The compilation and execution of UDPServer1.java (top) and UDPClient1.java (bottom)

5.3.2 Java TCP Client-Server Programming

Transmission Control Protocol is also a Transport layer protocol. Unlike UDP, TCP provides connection-oriented, reliable, streaming services. Because of TCP's error detection, error correction, and traffic flow control, TCP has been widely used in web, email, FTP download, and Telnet services, where the integrity of the data has the highest priority.

Example 5.7 is a simple TCP echo program. TCPServer1.java is the server program that provides an echo service. TCPClient1.java is the client program that sends a line of data to the server and prints the server's echo reply on screen.

The following is the TCPServer1.java (Example 5.7A) program's execution logic:

begin
    create a server TCP Socket on port 3301
    create a client Socket waiting for client's connection
    print client's IP address and port number
    create a BufferReader for receiving data from client
    create a DataOutputStream for sending data to client
    send data to client 
    close client Socket
    close server Socket
end

The following is the TCPClient1.java (Example 5.7B) program's execution logic:

begin
    create a BufferReader associating with keyboard
    create a client TCP Socket associating with a TCP server
    print server's IP address and port number
    create a DataOutputStream for sending data to server
    create a BufferReader for receiving data from server
    read in a line from keyboard and send it to server
    create a Datagram packet containing that line
    receive data from server and print server's response
    close Socket
end

Figure 5.11 shows the compilation and execution of the TCPServer1.java and TCPClient1.java programs. Again, you need to run TCPServer1.java first in a console window and then run TCPClient1.java in another console window. In this example, the TCP server runs on localhost (127.0.0.1) and on port 3301, and the TCP client runs on localhost (127.0.0.1) and on port 3020.

Screen capture depicting compilation and execution of the  TCPServer1.java (top) and TCPClient1.java (bottom) in Command Prompt.

Figure 5.11: The compilation and execution of TCPServer1.java (top) and TCPClient1.java (bottom)

5.3.3 Java Multithreaded EchoServer Programming

The echo server in the previous section runs on a single thread and therefore can accept only one client at a time. Example 5.8A shows a multithreaded echo server, which allows the echo server to accept multiple clients simultaneously and echo back the message from each client separately.

Example 5.8B shows the corresponding echo client.

For more information on Java socket programming, see the following resources:

https://docs.oracle.com/javase/tutorial/networking/sockets/index.html

https://www.javaworld.com/article/2077322/core-java/core-java-sockets-programming-in-java-a-tutorial.html

https://o7planning.org/en/10393/java-socket-programming-tutorial

5.4 Java HTTP Programming

HTTP stands for Hypertext Transfer Protocol; it is the protocol for communicating between web clients and servers. HTTP works on the basis of requests and responses, in which a web client (web browser) sends a request to the web server, and the web server responds with the result (a web page). HTTP is the magic behind the World Wide Web, which is no doubt the most popular service on the Internet today. With Java, you can easily develop web applications with HTTP.

5.4.1 A Java HTTP/HTTPS Client

Example 5.9 shows a series of Java HTTP clients—web clients. First, Example 5.9A is a simple client using the URL and URLConnection classes. In this example, it opens the web page specified by its uniform resource locator (URL), in this case www.google.com/. Figure 5.12 shows the compilation and execution of the program.

Screen capture depicting compilation and execution of the HTTPClient.java program in Command Prompt.

Figure 5.12: The compilation and execution of the HTTPClient.java program

Example 5.9B is a variation of the previous Java program, which uses HttpsURLConnection() to connect to a secure web site, using the HTTPS protocol.

Example 5.9C is a version of the same program, but it also prints the digital certificate information from the HTTPS server.

HTTP/HTTPS clients can use either the GET or POST method to talk to HTTP/HTTPS servers. The default is the GET method, which is used to retrieve information from the server. The POST method is for sending information to the server, such as sending login details, submitting forms, searching keywords, and similar tasks. Example 5.10 shows a simple Java HTTP/HTTPS client using the GET method to get information from the server, similar to the previous example. This version of the program opens the web page specified by its URL, in this case https://docs.oracle.com/javase/tutorial/. Figure 5.13 shows the compilation and execution of the program.

Screen capture depicting compilation and execution of the HTTPGet1.java program in Command Prompt.

Figure 5.13: The compilation and execution of the HTTPGet1.java program

Example 5.11 shows a simple Java HTTP client using the POST method to send search results to the server. In this example, it opens the web page https://www.amazon.co.uk/s/ref=nb_sb_noss_2? and searches for the keyword java. Figure 5.14 shows the compilation and execution of the program. Because of the output length, only the first 1,000 characters are printed. You can also search in another web site, such as Google; just uncomment the following two lines in the code:

         //String website="https://www.google.co.uk/search?";
         //String urlParameters="q=java"; 
Screen capture depicting compilation and execution of the HTTPPost1.java program in Command Prompt.

Figure 5.14: The compilation and execution of the HTTPPost1.java program

Example 5.12 shows another Java HTTP example using URL class. It parses the URL of a web page and shows the corresponding information such as the protocol, host, port, path, and query. Figure 5.15 shows the compilation and execution of the program.

Screen capture depicting compilation and execution of the URLExample1.java program in Command Prompt.

Figure 5.15: The compilation and execution of the URLExample1.java program

5.4.2 A Java HTTP Server

Example 5.13 shows a simple Java HTTP server program, using ServerSocket classes. It runs on port 8088, and when a web browser client is connected, it displays Hello World! in the browser. Figure 5.16 shows the compilation and execution of the program. To view the web page, open a web browser and type the IP address of your computer and port 8088, as shown in the figure.

Screen capture depicting compilation and execution of the HTTPServer.java program in Command Prompt (top) and testing the server using a web browser (bottom).

Figure 5.16: The compilation and execution of the HTTPServer.java program (top) and testing the server using a web browser (bottom)

5.4.3 Java Multithreaded HTTP Server

Example 5.14A is a multithreaded version of the previous HTTP server. In this version, it first creates a ServerSocket object on port 8088 and then uses a while loop to listen to client requests. Each time it accepts a client connection, it generates a separate thread dealing with that connection. Inside the thread, within the run() method, it reads all the lines of the HTTP request message from the client and sends back a Hello Multithreaded HTTP Server! message.

Example 5.14B is another multithreaded version of the earlier HTTP server. In this version, it finds out what file does the client request, finds and opens the file, reads line by line until finished, and also sends each line to the client accordingly. To test the HTTP server, just open a web browser and type the IP address of your computer and port 8088, exactly the same as in the previous figure.

5.5 Java Email SMTP Programming

Simple Mail Transfer Protocol is used to transfer email messages over the Internet. Example 5.15 shows a Java SMTP example. It connects to the email server at port 25, where SMTP is running, and uses HELO, MAIL, RCPT TO, DATA, and QUIT to send an email to a receiver.

A much more elegant and sophisticated way of sending and checking email is to use the JavaMail API. To use this API, you need to download two JAR files. For JavaMail, you need a file named javax.mail.jar, which you can get here:

https://javaee.github.io/javamail/

For the JavaBeans Activation Framework (JAF), you need a file named activation.jar, which you can get here:

https://www.oracle.com/technetwork/java/javase/downloads/index-135046.html

Find the javax.mail.jar and activation.jar files from the download, and copy them to your current Java directory. Example 5.16A shows a simple Java program for sending email through Transport Layer Security (TLS) using the JavaMail API. Please amend your SMTP server name, your username, your password, your email address, and recipient's email address accordingly. Please note that this code will not work if you have set up your email using two-factor or multifactor authentication, which requires you to present two or more pieces of evidence to log in.

To compile and run the Java program in Example 5.14A, you need to include the javax.mail.jar and activation.jar files in your classpath, as shown here:

javac -classpath .;javax.mail.jar;activation.jar  JavaMail1.java
java -classpath .;javax.mail.jar;activation.jar  JavaMail1

Example 5.16B shows another simple Java application for checking email using Post Office Protocol 3 (POP3). Again, it makes the connection through TLS using the JavaMail API. Please also amend the POP3 hostname, your username, and your password accordingly.

To compile and run the previous Java program, just type the following:

javac -classpath .;javax.mail.jar;activation.jar  JavaMail2.java
java -classpath .;javax.mail.jar;activation.jar  JavaMail2

For more information on SMTP and JavaMail, see the following resources:

https://en.wikipedia.org/wiki/Simple_Mail_Transfer_Protocol

https://www.oracle.com/technetwork/java/javamail/index.html

https://www.tutorialspoint.com/javamail_api/index.htm

https://www.journaldev.com/2532/javamail-example-send-mail-in-java-smtp

https://www.javatpoint.com/java-mail-api-tutorial

5.6 Java RMI Client-Server Programming

Remote method invocation (RMI) is a distributed systems technology that allows one Java virtual machine (JVM) to invoke object methods that will run on another JVM located elsewhere on a network. It is similar to remote procedure calls (RPCs), which were developed in the 1980s and allow a procedural program written in any language to call functions residing on another computer. But RPC supports only a limited set of simple data types, and it does not support objects. Although RMI currently supports only the Java language, it allows the passing and returning of Java objects, which makes it more powerful than RPC. RMI is useful for the development of large-scale systems, as it makes it possible to distribute resources and processing load across more than one machine.

RMI applications are divided into two kinds of programs: servers and clients. RMI servers create remote objects and register them with a lookup service to allow clients to find them. Clients use a remote reference to one or more remote objects in the server and then invoke methods on them.

To develop an RMI application, you need to create four programs.

  • The remote interface program
  • The remote interface implementation program
  • The RMI server program
  • The RMI client program

The remote interface program is a Java interface that defines the methods that can be called by clients. The remote interface implementation program implements the methods defined in the remote interface program. The RMI server program provides the service. Finally, the RMI client program uses the service. The remote interface, remote interface implementation, and RMI server programs run on the server computer, while the RMI client program runs on client computers.

Example 5.17 is a simple RMI application that can calculate the average of a series of double precision numbers. It contains four files, Analysor1.java, Analysor1Impl.java, Analysor1Server.java, and Analysor1Client.java. The file Analysor1.java is the interface program that defines only one method, called Average(). Analysor1Impl.java implements the Average() method. Analysor1Server.java provides an RMI service called AnalysorService, which contains the Average() method. By default, an RMI service runs on port 1099. The following are the two key statements of the server program:

       Analysor1 c = new Analysor1Impl();
       Naming.rebind("rmi://localhost:1099/AnalysorService", c);

Analysor1Client.java is the client program that will look for the AnalysorService service and call the Average() method. The following are the two key statements of the client program:

Analysor1 c = (Analysor1) Naming.lookup("rmi://localhost:1099/AnalysorService"); 
System.out.println( "The average of array d: "+ c.Average(d)); 

Example 5.17A is the Analysor1.java program.

Example 5.17B is the Analysor1Impl.java program.

Example 5.17C is the Analysor1Server.java program.

Example 5.17D is the Analysor1Client.java program.

To run an RMI application, follow these steps:

  1. Start the RMI registry so that RMI servers can register their services.
  2. Start the RMI servers.
  3. Start the RMI clients.

Figure 5.17 shows the details.

Screen capture depicting compilation of all the RMI Java programs and start of the RMI registry (top); the start of the A  alysor1Server.java RMI server (middle); and the start of the Analysor1Client.java RMI client (bottom) in Command Prompt.

Figure 5.17: The compilation of all the RMI Java programs and start of the RMI registry (top); the start of the Analysor1Server.java RMI server (middle); and the start of the Analysor1Client.java RMI client (bottom)

5.7 Getting Started with SDN

Earlier in the chapter you explored the concept of software-defined networking. This approach has shown huge potential and is definitely the future of computer networks. If you want to get started with SDN, the following are a few good places to begin. These tutorials will get you started with the most important SDN tools introduced earlier: OpenFlow, Floodlight, and OpenDaylight.

5.7.1 Getting Started with OpenFlow

The simplest way to get started with OpenFlow is to use Mininet. Figure 5.18 shows an interesting GitHub site (https://github.com/mininet/openflow-tutorial/wiki) on the OpenFlow tutorial. It shows how to download and set up the relevant software and shows examples such as Learn Development Tools, Create A Learning Switch, Control A Slice Of A Real Network, Router Exercise, Advanced Topology, and Create Firewall.

Image described by caption and surrounding text.

Figure 5.18: The GitHub site on the OpenFlow tutorial

To get started, you first need to download the following software:

  • Mininet VM Images

https://github.com/mininet/mininet/wiki/Mininet-VM-Images

  • VirtualBox

https://www.virtualbox.org/wiki/Downloads

  • Xming

https://sourceforge.net/projects/xming/files/Xming/6.9.0.31/Xming-6-9-0-31-setup.exe/download

  • Putty.exe

http://the.earth.li/~sgtatham/putty/latest/x86/putty.exe

Then follow the instructions at the following sites to import the Mininet virtual machine file into the VirtualBox software:

https://github.com/mininet/openflow-tutorial/wiki/Set-up-Virtual-Machine

http://mininet.org/vm-setup-notes/

Figure 5.19 shows the Mininet virtual machine in VirtualBox. Start the Mininet virtual machine, and use mininet for the username and mininet for the password to log in. The Mininet virtual machine is based on the Ubuntu Linux operating system.

Image described by caption and surrounding text.

Figure 5.19: The Mininet virtual machine in VirtualBox (top) and the Mininet login (bottom)

After login, at the Linux shell prompt ($), you can type the following command to start Mininet and enter its command-line interface (CLI) mode. The sudo command means you run the Mininet as a superuser, or administrator.

$ sudo mn

This will start a simulated network with minimal topology, which includes a controller (c0), a switch (s1), and two hosts (h1 and h2), as shown in Figure 5.20.

Schematic diagram depicting Mininet simulated network with controller (c0), a switch (s1), and two hosts (h1 and h2).

Figure 5.20: The Mininet simulated network with minimal topology

You can also start with other topologies by using the --topo option. For example, the following command starts a simulated network with single switch and four hosts:

$ sudo mn --topo single,4

The following command starts a simulated network with three switches connected in a line, and each has one host:

$ sudo mn --topo linear,3

You can use the following command to show more options of starting Mininet:

$ sudo mn -h

After starting Mininet CLI, at the mininet> prompt, type the following command to show all the nodes on the simulated network:

mininet> nodes

The following command shows network information on the simulated network:

mininet> net

The following command shows the information of all the links on the simulated network:

mininet> links

The following command shows more detailed information of all the nodes on the simulated network, including the IP address of each node:

mininet> dump

The following command shows the help information of all the Mininet CLI commands:

mininet> help

Figure 5.21 shows the output of some of the preceding commands in the Mininet virtual machine.

Image described by caption and surrounding text.

Figure 5.21: The Mininet commands to display information of the simulated network with minimal topology

The ifconfig command is a useful Linux command to display network information and to configure a network interface. It is similar to the Windows ipconfig command you used earlier. You can run the ifconfig command on the h1 node by typing the following command to display the network information for the h1 node:

mininet> h1 ifconfig

In this case, all the nodes use 10.0.0.0 IP addresses. Your simulated network might use different IP addresses, such as 192.168.0.0, depending on your computer network settings.

Similarly, the ps Linux command displays information about the processes running on the system. The ps -a command displays all the processes. You can run the ps -a command on the h1 node by typing the following command:

mininet> h1 ps -a

The ping Linux command can check the connections between two nodes. You can ping from host 1 to host 2 by typing the following command. The ping -c 10 command means to ping 10 times. Figure 5.22 shows the ping results.

Image described by caption and surrounding text.

Figure 5.22: The Mininet ping command to ping from host 1 to host 2 for 10 times

mininet> h1 ping -c 10 h2

You can also ping all nodes by typing the following command:

mininet> pingall

You can test the TCP bandwidth between the h1 node and the h2 node by typing the following command:

mininet> iperf

You can start the x terminal on the h1 node by typing the following command:

mininet> xterm h1

You can start a simple Python web server on the h1 node by typing the following command. The 80 means run the server on port 80, and & means to run the server in the background.

mininet> h1 python -m SimpleHTTPServer 80 &

You can view the web server content in text mode on the h2 node by typing the following command:

mininet> h2 wget -O - h1

You stop the Python web server on the h1 node by typing the following command:

mininet> h1 kill %python

You can also add new nodes to the network. The following are the steps. Type the following command to add a node called h3 to the network.

mininet> py net.addHost('h3')

Type the following command to add a new link between the s1 node and the h3 node:

mininet> py net.addLink(s1, net.get('h3'))

Type the following command to attach a new Ethernet interface on the s1 node:

mininet> py net.attach('s1-eth3')

Type the following command to configure the IP address for the h3 node:

mininet> py net.get('h3').cmd('ifconfig h3-eth0 10.0.0.3')

Type the following command to display the network information on the h3 node:

mininet> h3 ifconfig

Figure 5.23 shows the output of the preceding commands. As you can see, you should also be able to ping the h3 node from other nodes.

Image described by caption and surrounding text.

Figure 5.23: The commands to add and to configure a new node called h3 to the network

You can visualize the Mininet topology by using the online Mininet Topology Visualizer tool at the following web site:

http://demo.spear.narmox.com/app/?apiurl=demo#!/mininet

Just copy and paste the mininet> links results and the mininet> dump results into the page, and click the Render Graph button to generate the network topology, as shown in Figure 5.24.

Image described by caption and surrounding text.

Figure 5.24: The Mininet Topology Visualizer web site (top) and the generated topology graph (bottom)

Finally, you can exit the Mininet simulation by typing the following command:

mininet> exit

You can clean up the Mininet simulation by typing the following command:

$ sudo mn -c

For more information and advanced usage about Mininet OpenFlow, such as configuring the routers and switches, as well as using an Xming server, Putty.exe, and more, please visit the following resources:

https://github.com/mininet/openflow-tutorial/wiki

http://mininet.org/

https://github.com/mininet/mininet/wiki/Introduction-to-Mininet

https://academy.gns3.com/p/sdn-and-openflow-introduction

https://www.cisco.com/c/en_uk/solutions/software-defined-networking/overview.html

5.7.2 Getting Started with Floodlight

The following is the Project Floodlight web site. It has a detailed “get started” guide for instructions on how to download and install Floodlight.

http://www.projectfloodlight.org/getting-started/

5.7.3 Getting Started with OpenDaylight

The following is the wiki site of OpenDaylight. It shows how to download the OpenDaylight software and shows how to get started by setting up the development environment and getting the code.

https://wiki.opendaylight.org/view/Main_Page

5.8 Java Network Programming Resources

The following are a few interesting Java networking tutorials:

  • Tutorialspoint

https://www.tutorialspoint.com/java/java_networking.htm

  • Java2S

www.java2s.com/Tutorial/Java/0320__Network/javanetSocket.htm

  • GeeksforGeeks

https://www.geeksforgeeks.org/socket-programming-in-java/

5.9 Summary

This chapter introduced the basic concepts of computer networks, including the latest software-defined networking. It also provided some simple examples of using Java for network information, UDP sockets, TCP sockets, HTTP and HTTPS clients, HTTP servers, an SMTP client, a Java RMI client and server, and, finally, how to get started with SDN. More complicated Java examples based on the REST design model and the recent MQTT protocol are available in Chapter 7.

5.10 Chapter Review Questions

Q5.1. What is the Internet, and what is TCP/IP?
Q5.2. What are LANs and WANs?
Q5.3. What is Cisco's three-tier network architecture?
Q5.4. What is the difference between a switch and a router?
Q5.5. What are DNS and DHCP?
Q5.6. What is SDN? What are OpenFlow, Floodlight, and OpenDaylight?
Q5.7. What are IP addresses, port numbers, and MAC addresses?
Q5.8. What is the difference between IPv4 addresses and IPv6 addresses?
Q5.9. What is a socket?
Q5.10. What are the differences between UDP and TCP?
Q5.11. What is HTTP? How many versions does HTTP have? What is the difference between HTTP and HTTPS?
Q5.12. What is RMI, and how does RMI work?
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset