Advanced Programming---Chapter 5---Network Programming
6/26/23
Chapter 5: Network Programming
JAVA.NET PACKAGE
Overview: Networking 2
Networking is the concept of connecting multiple remote or local
6/26/23
Advanced Programming---Chapter 5---Network Programming
devices together.
Computers running on the Internet communicate to each other using
1. Transmission Control Protocol (TCP)
2. User Datagram Protocol (UDP)
Most Internet applications use TCP as their transport mechanism
Overview: Types of Communication 3
6/26/23
Advanced Programming---Chapter 5---Network Programming
Connection-oriented
Setup the link before communication.
Similar to the phone call. We need the phone number and receiver.
A reliable transport_
After it sends the data, it waits for an acknowledgment from the receiver to make sure that the data
reached the destination. _______
Connectionless
No link needed to be set up before communication.
Similar to sending a letter. We need the address and receiver.
It is unreliable, but much faster.
The sender will not wait to make sure the recipient received the packet rather continue sending
the next packets.
Overview: Protocol 6
6/26/23
Advanced Programming---Chapter 5---Network Programming
Protocol: set of rules and guidelines which provides the instructions to
send request and receive response over the network.
E.g., HTTP, FTP, TCP, UDP, SMTP, …
Whatever the service provided by a server, there must be some established protocol
governing the communication that takes place between server and client.
Internet Protocol(IP) Address: is an identification number that
uniquely identifies the computer on the Internet.
An IP address consists of four dotted decimal numbers between 0 and 255 e.g.,
192.168.2.01
Each computer on the Internet has a unique IP address
Overview: Port 7
6/26/23
Advanced Programming---Chapter 5---Network Programming
A computer has a single physical connection to the network.
All data destined for a particular computer arrives through that connection.
However, the data may be intended for different applications running on the computer.
So how does the computer know to which application to forward the data?
Through the use of ports.
Overview: Socket 10
6/26/23
Advanced Programming---Chapter 5---Network Programming
An interface between application and network.
Socket: a listener through which computer can receive requests and responses.
A server runs on a specific computer and has a socket that is bound to a specific port
number.
The server just waits, listening to the socket for a client to make a connection request.
On the client-side: The client knows the hostname of the machine on which the server is running
and the port number on which the server is listening.
A program can read from a socket or write to a socket as simply as reading from a file or writing
to a file.
Advanced Programming---Chapter 5---Network Programming
11
6/26/23
Overview: Socket
14
6/26/23
Advanced Programming---Chapter 5---Network Programming
Network Programming in Java
Network programming: writing programs that execute across multiple computers, in
which the devices are all connected to each other using a network.
Networking in Java 15
6/26/23
Advanced Programming---Chapter 5---Network Programming
Network programming usually involves a server and one or more clients.
1. The client sends requests to the server, and the server responds.
2. The client begins by attempting to establish a connection to the server.
3. The server can accept or deny the connection.
4. Once a connection is established, the client and the server communicate through sockets.
5. The server must be running when a client attempts to connect to the server.
6. The server waits for a connection request from a client.
7. The statements needed to create sockets on a server and a client
Networking is tightly integrated in Java.
Networking in Java 17
6/26/23
Advanced Programming---Chapter 5---Network Programming
Through the classes in java.net, Java programs can use TCP or UDP to
communicate over the Internet.
Stream-based communications: use TCP for data transmission
Socket, ServerSocket, URL, URLConnection classes are for use with TCP to
communicate over the network.
Packet-based communications : use UDP to communicate over the
network.
The DatagramPacket, DatagramSocket, and MulticastSocket classes are for use
with UDP.
18
6/26/23
Advanced Programming---Chapter 5---Network Programming
TCP based client server communication
Socket, ServerSocket, URL, URLConnection
TCP Communication 20
6/26/23
Advanced Programming---Chapter 5---Network Programming
The Java API provides TCP streams by means of two classes:
ServerSocket - This class implements server sockets. A server socket waits
for requests to come in over the network.
Socket - This class implements client sockets.
ServerSocket:
accept - Listens for a connection to be made to this socket and accepts it. The
result of executing accept is an instance of Socket.
Creating TCP Server Socket 21
6/26/23
Advanced Programming---Chapter 5---Network Programming
Five steps to create a simple stream server in Java:
1. ServerSocket object. Registers an available port and a maximum number of clients.
2. Each client connection handled with a Socket object. Server blocks until client
connects.
3. Sending and receiving data
OutputStream to send and InputStream to receive data.
Methods getInputStream and getOutputStream on Socket object.
4. Process phase. Server and client communicate via streams.
5. Close streams and connections.
Creating TCP Client Socket 22
6/26/23
Advanced Programming---Chapter 5---Network Programming
Four steps to create a simple stream client in Java:
1. Create a Socket object for the client.
2. Obtains Socket’s InputStream and/or OutputStream.
3. Process information communicated.
4. Close streams and Socket.
Advanced Programming---Chapter 5---Network Programming
23
6/26/23
Creating TCP Server/Client Socket
Accepting Connection 24
6/26/23
Advanced Programming---Chapter 5---Network Programming
Usually, the accept() method is executed within an infinite loop
i.e., while(true){...}
The accept method returns a new socket (with a new port) for the new
channel. It blocks until connection is made
Whenever accept() returns, a new thread is launched to handle that
interaction
Hence, the server can handle several requests concurrently
Serving Multiple Client 25
6/26/23
Advanced Programming---Chapter 5---Network Programming
Multiple clients are quite often connected to a single server at the
same time.
Typically, a server runs continuously on a server computer, and clients
from all over the Internet can connect to it.
You can use threads to handle the server’s multiple clients
simultaneously.
Simply create a thread for each connection.
Here is how the server handles the establishment of a
connection:
IP addressing Class 26
6/26/23
Advanced Programming---Chapter 5---Network Programming
For IP addressing, three classes are provided :
Inetaddress – for both IPv4 and IPv6
Inet4address – for IPv4
Inet6address – for Ipv6
Inetaddress class doesn’t have a constructor.
The normal way to create it is to call one of its static methods, such
as getByName, isReachable, getAllByName which throws exeption
Any program using this class must import either
java.net.InetAddress or java.net.*
Advanced Programming---Chapter 5---Network Programming
27
6/26/23
Example
URL Class 28
In Java, you handle URLs with the URL class.
6/26/23
Advanced Programming---Chapter 5---Network Programming
URL uniquely identifies or addresses information on the Internet.
Java’s URL class has several constructors (each can throw a
MalformedURLException) and methods.
The most commonly used constructors are:
URL(String spec)
URL(String protocol, String host, int port, String file)
URL(String protocol, String host, String file)
Purpose:
Get an input stream from a URL so you can read data from a server
Get content from the server as a Java object
The following methods of URL can be used for parsing URLs:
getProtocol(), getHost(), getPort(), getPath(),
getFile(), getQuery(), getRef()
Advanced Programming---Chapter 5---Network Programming
29
6/26/23
Parsing URL
Reading from a URLConnection 30
6/26/23
Advanced Programming---Chapter 5---Network Programming
The openConnection() method opens a socket to the specified URL
and returns a URLConnection object.
A URLConnection represents an open connection to a network
resource.
If the call fails, openConnection() throws an IOException.
After you've successfully created a URL, you can call the URL's
openConnection() method to get a stream from which you can
read the contents of the URL.
Advanced Programming---Chapter 5---Network Programming
31
6/26/23
Reading Directly from a URL
32
6/26/23
Advanced Programming---Chapter 5---Network Programming
UDP based Communication
DatagramPacket, DatagramSocket, and MulticastSocket
UDP Communication 33
6/26/23
Advanced Programming---Chapter 5---Network Programming
A datagram is an independent, self-contained message sent over the
network whose arrival, arrival time, and content are not guaranteed.
Java implements Datagram on top of the UDP protocol by using two
classes, namely the DatagramPacket and DatagramSocket
The DatagramPacket object is the data container
The DatagramSocket is the mechanism used to send or receive the
DatagramPacket.
UDP Communication 34
Datagram packets are used to implement a connectionless packet
6/26/23
Advanced Programming---Chapter 5---Network Programming
delivery service supported by the UDP protocol.
Each message is transferred from source machine to destination
based on information contained within that packet.
That means, each packet needs to have destination address and each packet
might be routed differently, and might arrive in any order.
Packet delivery is not guaranteed packet
UDP Communication 35
6/26/23
Advanced Programming---Chapter 5---Network Programming
The java.net.DatagramPacket: used to send datagram packets
The java.net.DatagramSocket: used to receive datagram packets
Sender does not wait for acknowledgements
Arrival order is not guaranteed
Arrival is not guaranteed.
So why use UDP if it unreliable?
Two reasons: speed and overhead.
USED when speed is essential, even in cost of reliability
– e.g. Streaming Media, Games, Internet Telephony, etc.
Send Datagram Packet 36
6/26/23
Advanced Programming---Chapter 5---Network Programming
STEPS TO SEND DATAGRAM PACKET
1. Create an array of bytes large enough to hold the data of the packet to be sent,
and fill the array with the data.
2. Create a new DatagramPacket object that contains the array of bytes, as well
as the server name and port number of the recipient.
3. A DatagramSocket is instantiated, and it is specified which port (and specific
localhost address, if necessary)
4. The send() method of the DatagramSocket class is invoked, passing in the
DatagramPacket object.
Receive Datagram Packet 37
6/26/23
Advanced Programming---Chapter 5---Network Programming
STEPS TO RECEIVE DATAGRAM PACKET
1. Create an array of bytes large enough to hold the data of the incoming packet.
2. A DatagramPacket object is instantiated using the array of bytes and its
length.
3. A DatagramSocket is instantiated, and it is specified which port (and specific
localhost address, if necessary) on the localhost the socket will bind to.
4. The receive() method of the DatagramSocket class is invoked, passing in the
DatagramPacket object. This causes the thread to block until a datagram
packet is received or a time out occurs.
Advanced Programming---Chapter 5---Network Programming
38
6/26/23
UDP Sender
Advanced Programming---Chapter 5---Network Programming
39
6/26/23
UDP Receiver
Advanced Programming---Chapter 5---Network Programming
40
6/26/23
End of Chapter 5
--- End ---