0% found this document useful (0 votes)
5 views41 pages

Chapter 4-Networking in Java

Chapter 4 discusses networking in Java, emphasizing the importance of the Internet and client-server computing. It explains key concepts such as IP addresses, sockets, and the differences between TCP and UDP protocols, including how to implement server and client applications in Java. The chapter also highlights the use of threads for handling multiple client connections and the advantages of UDP for speed in certain applications.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views41 pages

Chapter 4-Networking in Java

Chapter 4 discusses networking in Java, emphasizing the importance of the Internet and client-server computing. It explains key concepts such as IP addresses, sockets, and the differences between TCP and UDP protocols, including how to implement server and client applications in Java. The chapter also highlights the use of threads for handling multiple client connections and the advantages of UDP for speed in certain applications.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Chapter 4

Networking in Java

1
5/1/2025
Introductions
▪ Internet and WWW have emerged as global media for communication everywhere and
changed the way we conduct science, engineering, and commerce.

▪ They are also changing the way we learn, live, enjoy, communicate, interact, engage, etc.

▪ The modern life activities are getting completely centered around or driven by the Internet.

▪ The internet is all about connecting machines together.

▪ One of the most exciting aspects of Java is that it incorporates an easy-to-use, cross-
platform model for network communications that makes it possible to learn network
programming.

▪ This opens up a whole new class of applications to programmers.


5/1/2025 2
What is a network?
▪ A network is a collection of devices that share a common communication protocol and a

common communication medium (such as network cables, dial-up connections, and wireless

links).

▪ The term Network programming refers to writing programs that execute across multiple

devices (computers) in which the devices are all connected to each other using a network.

5/1/2025 3
Client-Server computing
▪ At a basic level, network-based systems consist of a server , client , and a media for
communication as shown in next slide figure.

▪ A computer running a program that makes a request for services is called client machine.

▪ A computer running a program that offers requested services from one or more clients is called
server machine.

▪ The media for communication can be wired or wireless network.

5/1/2025 4
Elements of Client -Server Computing

Client, Server, and Network

Client
Server
Network

Client machine
Server machine

5/1/2025 5
Hosts identification
▪ Every computer on the internet is identified by a unique, 4-byte IP address.

▪ This is typically written in dotted quad format like [Link] where each byte is an
unsigned value between 0 and 255.

▪ This representation is clearly not user-friendly because it does not tell us anything about the
content and then it is difficult to remember.

▪ Hence, IP addresses are mapped to names like [Link] or [Link], which are
easier to remember.

▪ Internet supports name servers that translate these names to IP addresses.

▪ Domain Naming Service (DNS) maps names to numbers.

5/1/2025 6
IP Addresses and Java

▪ Java has a class [Link] which abstracts network addresses.

✓ Performs name lookup (converting a host name into an IP address).

✓ Performs reverse lookup (converting the address into a host name).

▪ IP addresses are a 32-bit number, often represented as a "quad" of four 8-bit numbers separated
by periods.

▪ They are organized into classes (A, B, C, D, and E) which are used to group varying numbers of
hosts in a hierarchical numbering scheme.

5/1/2025 7
Service ports
▪ Each service offered by a computer is uniquely identified by a port number.
▪ Each internet packet contains both the destination host address and the port
number on that host to which the message/request has to be delivered.
▪ That is, IP address can be thought of as a house address when a letter is sent via
post/snail mail and port number as the name of a specific individual to whom the
letter has to be delivered.
▪ Port numbers range from 0 to 65,535.
▪ Ports 0 - 1024 are called well-known ports.
▪ They are reserved for use by well-known services:
• 20, 21: FTP
• 23: TELNET
• 25: SMTP
• 110: POP3
• 80: HTTP

5/1/2025 8
What is a Socket
▪ Sockets are a means of using IP to communicate between machines.
▪ So sockets are one major feature that allows Java to interoperate with legacy systems by
simply talking to existing servers using their pre-defined protocol.
▪ Sockets provide an interface for programming networks at the transport layer.
▪ Network communication using Sockets is very much similar to performing file I/O.
▪ In fact, socket handle is treated like file handle.
▪ The streams used in file I/O operation are also applicable to socket-based I/O.
▪ Socket-based communication is independent of a programming language used for
implementing it.
▪ That means, a socket program written in Java language can communicate to a program written
in non-Java (say C or C++) socket program.

5/1/2025 9
Cont. …

▪ Java’s fundamental networking capabilities are declared by classes and interfaces of the
[Link] package, through which Java offers stream-based communications.

▪ The classes and interfaces of [Link] also offer packet-based communications for
transmitting individual packets of information.

▪ This is most commonly used to transmit audio and video over the Internet.

▪ We will focus on both sides of the client-server relationship.

▪ The client requests that some action be performed, and the server performs the action and
responds to the client.

5/1/2025 10
Cont. …
▪ The [Link] package provides support for the two common network protocols:

1. TCP communication:

✓ Socket

✓ ServerSocket

2. UDP communication:

✓ DatagramPacket

✓ DatagramSocket

✓ MulticastSocket

5/1/2025 11
Socket Programming with TCP
▪ TCP (Transmission Control Protocol)

✓ A connection-oriented protocol.

✓ Allows reliable communication between two applications.

✓ Usually used over the Internet with IP as TCP/IP

✓ Resembles making a telephone call

• The person placing the telephone call – client

• The person waiting for a call – server

✓ The [Link] and [Link] classes are the only two classes you will
probably ever need to create a TCP/IP connection between two computers.

5/1/2025 12
TCP

▪ For a secure connection, SSLServerSocket and SSLSocket classes in the [Link]

package are used.

▪ Guarantees that data sent from one end of the connection actually gets to the other end and in

the same order it was sent.

▪ Otherwise, an error is reported.

▪ The Hypertext Transfer Protocol (HTTP), File Transfer Protocol (FTP), and Telnet are all

examples of applications that require a reliable communication channel.

5/1/2025 13
Sockets and Java Socket Classes

▪ A program can read from a socket or write to a socket as simply as reading from a file or
writing to a file.

▪ A socket is bound to a port number so that the TCP layer can identify the application that data
destined to be sent.

▪ Java’s .net package provides two classes:

1. Socket – for implementing a client.

2. ServerSocket – for implementing a server.

5/1/2025 14
Socket Communication
▪ A server (program) runs on a specific computer and has a socket that is bound to a specific
port.
▪ The server waits and listens to the socket for a client to make a connection request.

Connection request Client

port
server

Fig. Client making connection request to server

5/1/2025 15
Cont. …
▪ If everything goes well, the server accepts the connection.
▪ Upon acceptance, the server gets a new socket bounds to a different port.
▪ It needs a new socket (consequently a different port number) so that it can continue to
listen to the original socket for connection requests while serving the connected client.

port
server

port
Client
port Connection

Fig. Session established with temporary ports used for two way communication

5/1/2025 16

ServerSocket(1234)
Server

Output/write stream Client

Input/read stream

Socket(“[Link]”, 1234)

Socket-based client and server programming

5/1/2025 17
Socket operations
▪ There are four fundamental operations a socket performs.

▪ These are:
✓ Connect to a remote machine
✓ Send data
✓ Receive data
✓ Close the connection

▪ The [Link] class allows you to perform all four fundamental socket operations.

5/1/2025 18
Cont. …
▪ Socket class represents the socket that both the client and server use to communicate with

each other.

▪ Connection is accomplished through the constructors.

▪ Each Socket object is associated with exactly one remote host.

▪ To connect to a different host, you must create a new Socket object.

5/1/2025 19
Socket methods
▪ There are methods to return information about the socket.

✓ InetAddress getInetAddress()

✓ InetAddress getLocalAddress()

✓ int getPort()//Returns the port the socket is bound to on the remote machine.

✓ int getLocalPort()//Returns the port the socket is bound to on the local machine.

5/1/2025 20
ServerSocket methods
1. public int getLocalPort()
✓ Returns the port that the server socket is listening on.
2. public Socket accept() throws IOException
✓ Waits for an incoming client.
✓ This method blocks until either a client connects to the server on the specified port or
the socket times out.

3. public void setSoTimeout(int timeout)

✓ Sets the time-out value for how long the server socket waits for a client during the
accept().

5/1/2025 21
Establishing a Simple Server Using Stream Sockets
Five steps to create a simple stream server in Java:
1. Open the Server Socket: Each client connection handled with a Socket object. Server blocks until client
connects.
ServerSocket server = new ServerSocket( PORT );
[Link] for the Client Request.
Socket client = [Link]();
[Link] I/O streams for communicating to the client
DataInputStream is = new DataInputStream([Link]());
DataOutputStream os = new DataOutputStream([Link]());
4. Perform communication with client
Receive from client: String line = [Link]();
Send to client: [Link](“Hello\n”);
5. Close socket:
[Link]();

5/1/2025 22
Establishing a Simple Client Using Stream Sockets
Four steps to create a simple stream client in Java:
[Link] a Socket Object: Obtains Socket’s InputStream and OutputStream.
Socket client = new Socket(server, port_id);
2. Create I/O streams for communicating with the server.
is = new DataInputStream([Link]());
os = new DataOutputStream([Link]());
3. Perform I/O or communication with the server:
Receive data from the server: String line = [Link]();
Send data to the server: [Link](“Hello\n”);
4. Close the socket when done:
[Link]();

5/1/2025 23
Example: Java server using TCP

//simple server application using TCP


import [Link].*;
import [Link].*;
class TCPServer {
public static void main (String args[]) throws Exception {
String clientSentence;
String capitalizedSentence;
//create welcoming socket at port 6789
ServerSocket welcomeSocket = new ServerSocket(6789);
while (true) {
//block on welcoming socket for contact by a client
Socket connectionSocket = [Link]();
//create input stream attached to socket
BufferedReader inFromClient = new BufferedReader(new
InputStreamReader
([Link]()));

5/1/2025 24
Example: Java server using TCP (cont.)
//createoutput stream attached to socket
DataOutputStream outToClient = new
DataOutputStream([Link]()); //read in
line from the socket
clientSentence = [Link]();
//process
capitalizedSentence = [Link]() + '\n';
//write out line to socket
[Link](capitalizedSentence);
} }}

5/1/2025 25
Java client using TCP
//simple client application using TCP
import [Link].*;
import [Link].*;
class TCPClient {
public static void main (String args[]) throws Exception{
String sentence;
String modifiedSentence;
//create input stream
BufferedReader inFromUser = new BufferedReader(new
InputStreamReader([Link]));
//create client socket and connect to server
Socket clientSocket = new Socket("localhost", 6789);
//create output stream attached to socket
DataOutputStream outToServer = new
DataOutputStream([Link]());
5/1/2025 26
Java client using TCP (cont.)
//create input stream attached to socket
BufferedReader inFromServer = new BufferedReader(new InputStreamReader
([Link]()));
sentence = [Link]();
//send line to server
[Link](sentence + '\n');
//read line from server
modifiedSentence = [Link]();
[Link]("FROM SERVER: " + modifiedSentence);
[Link]();
}
}

5/1/2025 27
Serving Multiple Clients
▪ Multiple clients are quite often connected to a single server at the same time.

▪ Typically, a server runs constantly on a server computer, and clients from all over the Internet
may want to 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:


while (true) {
Socket socket = [Link]();
Thread thread = new ThreadClass(socket);
[Link]();}
5/1/2025 28
Cont. …

▪ The server socket can have many connections.

▪ Each iteration of the while loop creates a new connection.

▪ Whenever a connection is established, a new thread is created to handle communication

between the server and the new client; and this allows multiple connections to run at the

same time.

5/1/2025 29
Socket Programming with UDP
▪ UDP (User Datagram Protocol)

▪ A connectionless protocol.

▪ Because the packets have no relationship to each other.

▪ Allows packets of data (datagram) to be transmitted between applications.

▪ Resembles mailing someone a letter.

✓ The datagram packet is like a letter, where a client sends a datagram to a server without
actually connecting to the server.

✓ This makes UDP an unreliable protocol.

5/1/2025 30
UDP
▪ UDP does not guarantee that packets will be received in the order they were sent or that they will even be
delivered at all.

✓ The [Link] class – to send datagram packets

✓ The [Link] class – 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.

5/1/2025 31
Cont …

DatagramSocket DatagramPacket

▪ Used to create a UDP server/client. ▪ Create a datagram packet.

▪ It sends and receive datagram packet. ▪ Objects store packet of data that are to be

sent or that are received by an

application.

5/1/2025 32
Cont. …
▪ Datagram sockets transmit individual packets of information.

▪ This is typically not appropriate for use by everyday programmers because the transmission
protocol is UDP (User Datagram Protocol).

▪ UDP provides a connectionless service.

▪ A connectionless service does not guarantee that packets arrive at the destination in any
particular order.

▪ With UDP, packets can be lost or duplicated.

▪ UDP is most appropriate for network applications that do not require the error checking and
reliability of TCP.
5/1/2025 33
Cont. …
▪ Under UDP there is no “connection” between the server and the client.

▪ There is no “handshaking”.

▪ The sender explicitly attaches the IP address and port of the destination to each packet.

▪ The server must extract the IP address and port of the sender from the received packet.

▪ From an application viewpoint, UDP provides unreliable transfer of groups of bytes


(“datagrams”) between client and server.

5/1/2025 34
Steps to Receive a Datagram packet - UDP
▪ Create an array of bytes large enough to hold the data of the incoming packet.

byte[] buffer = new byte[1024];

▪ A DatagramPacket object is instantiated using the array of bytes.

DatagramPacket packet =new DatagramPacket(buffer, [Link]);

▪ A DatagramSocket is instantiated, and it is specified which port (and specific localhost


address, if necessary) on the localhost the socket will bind to.

int port = 1234;

DatagramSocket socket = new DatagramSocket(port);

5/1/2025 35
Cont …
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.
// Block on receive()
[Link](packet);
// Find out where packet came from so we can reply to the same host/port

InetAddress remoteHost = [Link]();

int remotePort = [Link]();

// Extract the packet data

byte[] data = [Link]();


5/1/2025 36
Steps to Send a Datagram packet - UDP
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.
byte[] buffer = new byte[1024];

2. Create a new DatagramPacket object that contains the array of bytes, as well as the server name and port number
of the recipient.

int port = 1234;

InetAddress host =[Link](“[Link]");

DatagramPacket packet =new DatagramPacket(buffer, [Link], host, port);


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.
DatagramSocket socket = new DatagramSocket();

4. The send() method of the DatagramSocket class is invoked, passing in the DatagramPacket object.

5/1/2025 37
Example: Java server using UDP
import [Link].*;
import [Link].*;
class UDPServer {
public static void main(String args[]) throws Exception
{ //Create datagram socket on port 9876
DatagramSocket serverSocket = new
DatagramSocket(9876);
byte[] sendData = new byte[1024];
byte[] receiveData = new byte[1024];
while (true)
{ //create space for the received datagram
DatagramPacket receivePacket = new DatagramPacket(receiveData,
[Link]);
//receive the datagram
[Link](receivePacket);
String sentence = new String([Link]());

5/1/2025 38
Cont …

//get IP address and port number of sender


InetAddress IPAddress = [Link]();
int port = [Link]();
String capitalizedSentence =[Link]();
sendData = [Link]();
//create datagram to send to client
DatagramPacket sendPacket = new DatagramPacket(sendData,
[Link], IPAddress, port);
//write out the datagram to the socket
[Link](sendPacket);
} //end while loop }}

5/1/2025 39
Example: Java client using UDP
import [Link].*;
import [Link].*;
class UDPClient {
public static void main(String args[]) throws Exception
{ //Create input stream
BufferedReader inFromUser = new BufferedReader(new
InputStreamReader([Link]));
//Create client socket
DatagramSocket clientSocket = new DatagramSocket();
//Translate hostname to IP address using DNS
InetAddress IPAddress = [Link]("localhost");
byte[] sendData = new byte[1024];
byte[] receiveData = new byte[1024];
String sentence = [Link]();
sendData = [Link]();

5/1/2025 40
Cont …

DatagramPacket sendPacket = new DatagramPacket(sendData, [Link],


IPAddress, 9876);
[Link](sendPacket);
DatagramPacket receivePacket = new DatagramPacket(receiveData,
[Link]);
[Link](receivePacket);
String modifiedSentence = new String([Link]());
[Link]("FROM SERVER: " + modifiedSentence);
[Link]();
}
}

5/1/2025 41

You might also like