0% found this document useful (0 votes)
2 views74 pages

Chapter Four Netwk Programming

Java network programming

Uploaded by

singitannuguse
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)
2 views74 pages

Chapter Four Netwk Programming

Java network programming

Uploaded by

singitannuguse
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

Question from previous chapter on non relational databases

Non-relational databases, also known as NoSQL databases, are designed to handle


unstructured, semi-structured, or structured data, offering flexibility, scalability, and
performance for modern applications. Unlike relational databases (e.g., MySQL,
PostgreSQL) that use tables, rows, and SQL for structured data, NoSQL databases
use various data models like document, key-value, column-family, or graph to store
and retrieve data.

• Java interacts with NoSQL databases through database-specific


drivers or APIs provided by the database vendor or community.
• These drivers act as a bridge between the Java application and the • Connection Management: Java establishes a
database, enabling operations like connection management,
CRUD (Create, Read, Update, Delete), indexing, and aggregation.
connection to the NoSQL database using a
Here’s a breakdown of the process: connection string or configuration.
• Driver Integration:
• Each NoSQL database provides a Java driver (e.g., MongoDB Java
• Drivers often support connection pooling to
Driver, Cassandra Java Driver, Neo4j Java Driver). manage multiple connections efficiently.
• The driver is included as a dependency in the Java project (e.g., via
Maven or Gradle). • Example: MongoDB’s MongoClient
• Example: For MongoDB, the mongodb-driver-sync library is used. connects to a MongoDB server.

1
CHAPTER FOUR :
NETWORK PROGRAMMING

2
Networking Basics
• Computer networking is to send and receive messages among computers
on the Internet

• To browse the Web or send email, your computer must be connected to


the Internet.
• Your computer can connect to the Internet through an Internet Service
Provider (ISP) using a dialup, DSL, or cable modem, or through a local
area network (LAN).
• Java Networking is a concept of connecting two or more computing
devices together so that we can share resources.
• Advantage of Java Networking
– sharing resources
– centralize software management

• When a computer needs to communicate with another computer, it needs


to know an IP address.
3
Networking Basics
• Internet Protocol (IP) addresses
– Uniquely identifies the computer on the Internet. or
– IP address is a unique number assigned to a node of a
network. – Since it is difficult to remember IP address, there is a special server
– It is a logical address that can be changed. called Domain Name Server(DNS), which translates hostname to IP
– Every host on Internet has a unique IP address address
– An IP address consists of four dotted decimal numbers – Example: DomainName: [Link] , [Link], localhost
ranging from IP Addresess:[Link] , [Link] [Link]

0 and 255, such as – One domain name can correspond to multiple internet addresses:
[Link], [Link] • [Link]:
[Link], [Link], [Link]; [Link]; [Link]; [Link]; …

127.0.0. – Domain Naming Service (DNS) maps names to numbers

4
Networking Basics

⚫ Port Number
▪ The port number is used to uniquely identify different applications.
▪ It acts as a communication endpoint between applications.
▪ The port number is associated with the IP address for communication between two applications.
▪ Port numbers are ranging from 0 to 65536, but port numbers 0 to 1024 are reserved for privileged services.
▪ Many standard port numbers are pre-assigned
▪ time of day 13, ftp 21, telnet 23, smtp 25, http 80
▪ You can choose any port number that is not currently used by other programs.
▪ IP address + port number = "phone number“ for service or application
⚫ MAC Address
▪ MAC (Media Access Control) Address is a unique identifier of NIC (Network Interface Controller).
▪ A network node can have multiple NIC but each with unique MAC.

5
Networking Basics
⚫ A protocols is a set of rules that facilitate communications between machines or hosts.
⚫ Examples:
▪ HTTP: HyperText Transfer Protocol
▪ FTP: File Transfer Protocol
▪ SMTP: Simple Message Transfer Protocol
▪ TCP: Transmission Control Protocol
▪ UDP: User Datagram Protocol, good for, e.g., video delivery)

⚫ TCP:
▪ Connection-oriented protocol
▪ enables two hosts to establish a connection and exchange streams of data.
▪ Acknowledgement is send by the receiver. So, it is reliable but slow
▪ Uses Stream-based communications
▪ guarantees delivery of data and also guarantees that packets will be delivered in the same
order in which they were sent.
⚫ UDP:
▪ Enables connectionless communication
▪ Acknowledgement is not sent by the receiver. So it is not reliable but fast.
▪ Uses packet-based communications.
▪ Cannot guarantee lossless transmission. 6
Networking Basics
⚫ Client-Server interaction
⚫ Communication between hosts is two-way, but usually the two hosts take different roles.
⚫ Server waits for client to make request
Server registered on a known port with the host ("public phone number") Listens for incoming client

connections

⚫ Client "calls" server to start a conversation


Client making calls uses hostname/IP address and port number
Sends request and waits for response

⚫ Standard services always running


ftp, http, smtp, etc. server running on host using expected port

⚫ Server offers shared resource (information, database, files, printer, compute power)
to clients 7
Client server communication
How Java handle such issues
Client
Request

Response
Client
Server
.
.
.
Client

8
Introduction
• 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.
• The [Link] package of the J2SE(Java 2 Platform,
Standard Edition) APIs contains a collection of
classes and interfaces that provide the low-level
communication details

•The [Link] package provides support for the two common network protocols:
• TCP: allows for reliable communication between two applications.
• is typically used over the Internet Protocol, which is referred to as TCP/IP.
• UDP: is a connection-less protocol that allows for packets of data to be transmitted between applications.

9
Socket-Level Programming
⚫ Java Socket programming is used for communication between the applications
running on different JRE.
⚫ Java Socket programming can be connection-oriented or connection-
less.
⚫ Socket and ServerSocket classes are used for connection-oriented socket
programming.
⚫ DatagramSocket and DatagramPacket classes are
used for connection-less socket programming.
⚫ Java socket programming provides facility to share data between different
computing devices.
⚫ Send and receive data using streams
OutputStream InputStream
Client Server

InputStream OutputStream 7
TCP
• Java provides the ServerSocket class for creating a server socket and the Socket class for creating a client
socket.
• Two programs on the Internet communicate through a server socket and a client socket using I/O streams.
• Sockets are the endpoints of logical connections between two hosts and can be used to send and receive data.
• Network programming usually involves a server and one or more clients.
• The client sends requests to the server, and the server responds.
• The client begins by attempting to establish a connection to the server.
• The server can accept or deny the connection.
• Once a connection is established, the client and the server communicate through sockets.
• The server must be running when a client attempts to connect to the server.

• The server waits for a connection request from a


client.
8
Socket Programming
• Sockets provide the communication mechanism
between two computers using TCP.
• A client program creates a socket on its end of the
communication and attempts to connect that socket
to a server.

• When the connection is made, the server creates a


socket object on its end of the communication.
• The client and server can now communicate by
writing to and reading from the socket.

• The [Link] class represents a socket, and


• The [Link] class provides a
mechanism for the server program to listen for clients
and establish connections with them.

12
Key package and classes

13
Client/Server Communications
The statements needed to create
sockets on a server and a client
are shown below.

14
• The following steps occur when establishing a TCP
connection between two computers using
sockets:
• The server instantiates a ServerSocket object, denoting which port number
communication is to occur on.
• The server invokes the accept() method of the ServerSocket class. This method waits
until a client connects to the server on the given port.

• After the server is waiting, a client instantiates a Socket object, specifying the server
name and port number to connect to.
• The constructor of the Socket class attempts to connect the client to the specified server
and port number.
• If communication is established, the client now has a Socket object capable of communicating with
the server.

• On the server side, the accept() method returns a reference to a new socket on the
server that is connected to the client's socket.

15
• After the connections are established, communication can occur using I/O streams.
• Each socket has both an OutputStream and an InputStream.
• The client's OutputStream is connected to the server's InputStream, and
• The client's InputStream is connected to the server's OutputStream.

• TCP is a two way communication protocol, so data can be sent across both streams at
the same time.

16
Server Sockets
• To establish a server, you need to create a server socket and
attach it to a port, which is where the server listens for
connections.
• The port identifies the TCP service on the socket.
• The following statement creates a server socket
serverSocket:

ServerSocket serverSocket = new ServerSocket(port);

• Attempting to create a server socket on a port already in use


would cause the [Link].

17
Client Sockets
• After a server socket is created, the server can use the following
statement to listen for connections:
Socket socket = [Link]();
• This statement waits until a client connects to the server socket.
• The client issues the following statement to request a connection
to a server:
Socket socket = new Socket(serverName, port);
• This statement opens a socket so that the client program can
communicate with the server.

18
Client Sockets
• serverName is the server’s Internet host name or IP address.
• The following statement creates a socket on the client machine
to connect to the host [Link] at port 8000:

• Socket socket = new Socket("[Link]", 8000)

• Alternatively, you can use the domain name to create a socket,


as follows: [Link]

Socket socket = new Socket(“[Link]", 8000);

• When you create a socket with a host name, the JVM asks the
DNS to translate the host name into the IP address.

19
Data Transmission through
Sockets
• After the server accepts the connection, communication
between the server and client is conducted the same as for
I/O streams.

• The statements needed to create the streams and to


exchange data between them are shown in the Figure below.

20
Data Transmission through Sockets

21
Data Transmission through Sockets
• To get an input stream and an output stream, use the getInputStream()
and getOutputStream() methods on a socket object.

• For example, the following statements create an InputStream stream


called input and an OutputStream stream called output from a
socket:

InputStream input =[Link]();

OutputStream output = [Link]();

22
Data Transmission through Sockets
• The InputStream and OutputStream streams are used to read or write bytes.
• You can use DataInputStream, DataOutputStream, BufferedReader, and
PrintWriter to wrap on the InputStream and OutputStream to read or write
data, such as int, double, orString.
•The following statements, for instance, create the DataInputStream stream input
and the DataOutput stream output to read and write primitive data values:

DataInputStream input = new DataInputStream ([Link]());


DataOutputStream output = new DataOutputStream ([Link]());

•The server can use [Link]() to receive a double value from the client, and [Link](d) to
send the double value d to the client.
•Binary I/O is more efficient than text I/O because text I/O requires encoding and decoding.
•Therefore, it is better to use binary I/O for transmitting data between a server and a client to improve
performance.

23
ServerSocket Class
• The [Link] class is used by server applications to obtain a port and
listen for client requests.
• Constructors

• All the four constructors throws IOException.


• ServerSocket(int port): Attempts to create a server socket bound to the specified port.
• ServerSocket(int port, int backlog): Similar to the previous constructor, the backlog parameter
specifies how many incoming clients to store in a wait queue.
• ServerSocket(int port, int backlog, InetAddress address): the InetAddress parameter specifies
the local IP address to bind to.
• The InetAddress is used for servers that may have multiple IP addresses, allowing the server to specify
which of its IP addresses to accept client requests on.
• ServerSocket(): Creates an unbound server socket.
• using this constructor, use the bind() method when you are ready to bind the server socket.

24
Cont.
• Common Methods
• int getLocalPort(): Returns the port that the server socket is listening on.
• This method is useful if you passed in 0 as the port number in a constructor and let the server
find a port for you.
• Socket accept(): 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, assuming that the time-out value has been set using the setSoTimeout()
method Otherwise, this method blocks indefinitely

25
Cont.
• void setSoTimeout(int timeout): Sets the time-out value for how long the server
socket waits for a client during the accept().
• public void bind(SocketAddress host, int backlog): Binds the socket to the specified
server and port in the SocketAddress object.
• Use this method if you instantiated the ServerSocket using the no-argument constructor.

• After a client does connect, the ServerSocket creates a new Socket on an


unspecified port and returns a reference to this new Socket.
• A TCP connection now exists between the client and server, and communication
can begin.

26
Socket Class

• The [Link] class represents the socket that both the client and server use to
communicate with each other.

• The client obtains a Socket object by instantiating


one, whereas the server obtains a Socket object
from the return value of the accept() method.
Java Sockets
• Java wraps OS sockets (over TCP) by the objects of class
[Link]
• new Socket(String remoteHost, int remotePort)
creates a TCP socket and
connects it to the remote host on the remote port (hand shake)
• Write and read using streams:
• InputStream getInputStream()
• OutputStream getOutputStream()
• The Socket class has five constructors that a client uses to connect to a server:
1. Socket(String host, int port): attempts to connect to the specified server at the
specified port.
• throws UnknownHostException, IOException

3. Socket(String host, int port, InetAddress


2. Socket(InetAddress host, int port): is identical to localAddress, int localPort): Connects to the
the previous constructor, except that the host is specified host and port, creating a socket on the local
denoted by an InetAddress object. host at the specified address and port.
throws IOException throws IOException

4. Socket(InetAddress host, int port,


InetAddress localAddress, int localPort): is 5. Socket(): Creates an unconnected socket.
identical to the previous constructor, except that the Use the connect() method to connect
host is denoted by an InetAddress object instead of this socket to a server.
a String
• throws IOException

29
Cont.
• Notice that both the client and server have a Socket object, so these methods can be
invoked by both the client and server.

• Some methods in the Socket class are:


• void connect(SocketAddress host, int timeout) throws IOException: connects the socket
to the specified host.
• is needed only when you instantiated the Socket using the no-argument constructor.
• InetAddress getInetAddress(): returns the address of the other computer that this socket
is connected to.
• 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.
• SocketAddress getRemoteSocketAddress(): Returns the address of the remote socket.

30
• InputStream getInputStream() throws IOException: Returns the input stream of the
socket.
• The input stream is connected to the output stream of the remote socket.
• OutputStream getOutputStream() throws IOException: Returns the output stream of
the socket.
• The output stream is connected to the input stream of the remote socket
• void close() throws IOException: Closes the socket, which makes this Socket object no
longer capable of connecting again to any server

31
InetAddress Class
• represents an Internet Protocol (IP) address
• useful methods which you would need while doing socket programming:
• InetAddress getByAddress(byte[] addr): Returns an InetAddress object given the raw IP
address.
• InetAddress getByAddress(String host, byte[] addr): Create an InetAddress based on
the provided host name and IP address.
• InetAddress getByName(String host): Determines the IP address of a host, given the
host's name.
• String getHostAddress(): Returns the IP address string in textual presentation.
• String getHostName() Gets the host name for this IP address.
• InetAddress getLocalHost(): Returns the local host.
• String toString(): Converts this IP address to a String.

32
A Client/Server Example
• Problem: Write a client and a server program that the
client sends data to a server. The server receives the data,
uses it to produce a result, and then sends the result back
to the client. The client displays the result on the console.
In this example, the data sent from the client is the radius
of a circle, and the result produced by the server is the
area of the circle. The client sends the radius to the
server; the server computes the area and sends it to the
client.
compute area
radius

Server Client
area

33
A Client/Server Example
• The client sends the radius through a DataOutputStream on the output stream socket, and
the server receives the radius through the DataInputStream on the input stream socket, as
shown in Figure (A) below.
• The server computes the area and sends it to the client through a DataOutputStream on the
output stream socket, and the client receives the area through a DataInputStream on the
input stream socket, as shown in Figure (B) below.

Server Client Server Client


radius radius area area

DataInputStream DataOutputStream DataOutputStream DataOutputStream

[Link] [Link] [Link] [Link]

socket socket socket socket

Network Network

(A) (B) 18
Socket Client Example:
• The following GreetingClient is a client program that connects to a
server by using a socket and sends a greeting, and then waits for a
response.
import [Link].*;
import [Link].*;
public class GreetingClient {
public static void main(String [] args) {
String serverName = args[0];
int port = [Link](args[1]);
try {
[Link]("Connecting to " +
serverName + " on port " + port);
Socket client = new Socket(serverName, port);

35
[Link]("Just connected to " +
[Link]());
OutputStream outToServer =
[Link]();
DataOutputStream out = new
DataOutputStream(outToServer);
[Link]("Hello from " +
[Link]());
InputStream inFromServer =
[Link]();
DataInputStream in = new
DataInputStream(inFromServer);
[Link]("Server says " +
[Link]());
[Link]();
}catch(IOException e) {
[Link]();
}
} }

36
Socket Server Example:
• The following GreetingServer program is an example of a server
application that uses the Socket class to listen for clients on a port
number specified by a command-line argument:
import [Link].*;
import [Link].*;
public class GreetingServer extends Thread {
private ServerSocket serverSocket;
public GreetingServer(int port) throws IOException {
serverSocket = new ServerSocket(port);
[Link](10000);
}

37
public void run() {
while(true) {
try {
[Link]("Waiting for client on port " +
[Link]() + "...");
Socket server = [Link]();
[Link]("Just connected to " +
[Link]());
DataInputStream in = new
DataInputStream([Link]());
[Link]([Link]());
DataOutputStream out = new
DataOutputStream([Link]());
[Link]("Thank you for connecting to " +
[Link]() + "\nGoodbye!");
[Link]();
}
38
catch(SocketTimeoutException s) {
[Link]("Socket timed out!");
break;
}catch(IOException e) {
[Link]();
break;
}
}
}
public static void main(String [] args) {
int port = [Link](args[0]);
try {
Thread t = new GreetingServer(port);
[Link]();
}catch(IOException e) {
[Link]();
}}}

39
UDP Clients and Servers

• UDP (User Datagram Protocol) is a connectionless


transport layer protocol that is often used for
applications that require low latency and do not
require guaranteed delivery of packets.

• In contrast to TCP, UDP does not establish a


connection before transmitting data, and there is
no error checking or retransmission of lost packets.
• Here's an example of a simple UDP server and
client in Java:
Cont…
• is implemented using the
DatagramSocket and DatagramPacket
classes from the [Link] package.
• Java supports UDP through the following
two main classes from [Link]:
• DatagramSocket Used to send and receive
UDP [Link] like a mailbox for sending
or receiving datagrams on a specific port.
• DatagramPacket Represents the actual
data being sent or received.

41
import [Link].*; import [Link].*;
import [Link].*; import [Link].*;

public class UDPServer {


public class UDPClient {

public static void main(String[] args) {


UDP CLIENT
public static void main(String[] args) { try {
try { // create a DatagramSocket and bind it to port 1234 DatagramSocket clientSocket = new DatagramSocket(); // create a DatagramSocket

DatagramSocket serverSocket = new DatagramSocket(1234); // create a byte array to hold the message to send
[Link]("UDP Server is running on port " + String message = "Hello, server!";
[Link]());
byte[] sendData = [Link]();
// create a byte array to hold incoming data InetAddress serverAddress = [Link]("localhost");
byte[] receiveData = new byte[1024]; int serverPort = 1234;
// create a DatagramPacket to receive incoming packets DatagramPacket sendPacket = new DatagramPacket(sendData, [Link],
serverAddress, serverPort); // create a DatagramPacket to send to the server
DatagramPacket receivePacket = new DatagramPacket(receiveData,
[Link]); [Link](sendPacket); // send the packet to the server
while (true) { // wait for incoming packets [Link](receivePacket); [Link]("Sent message: " + message + " to " + serverAddress + ":" +

UDP // extract the data from the packet


String message = new String([Link](), 0, [Link]());
InetAddress clientAddress = [Link]();
serverPort);
byte[] receiveData = new byte[1024]; // create a byte array to hold the incoming
data

SERVER int clientPort = [Link](); [Link]("Received message: " + message +


" from " + clientAddress + ":" + clientPort);
// send a response to the client
// create a DatagramPacket to receive the response from the server DatagramPacket
receivePacket = new DatagramPacket(receiveData, [Link]);
// wait for the response from the server [Link](receivePacket);
// extract the data from the packet
String response = "Hello, client!";
byte[] sendData = [Link](); String response = new String([Link](), 0, [Link]());
DatagramPacket sendPacket = new DatagramPacket(sendData, [Link],
InetAddress server = [Link]();
clientAddress, clientPort); [Link](sendPacket); int port = [Link](); [Link]("Received message: " + response
[Link]("Sent message: " + response + " to " + clientAddress + ":" + clientPort); + " from " + server + ":" + port); // close the socket [Link]();
} catch (IOException e) {
}
[Link]();
} }
catch (IOException e) { }
[Link](); }
}
• start server as follows:
• $ java GreetingServer 6000

• Check client program as follows:


• $ java GreetingClient localhost 6000

43
cont…

44
DatagramSocket and DatagramPacket
• Java DatagramSocket and DatagramPacket classes are used for connection-less
socket programming.
• DatagramSocket class
• represents a connection-less socket for sending and receiving datagram packets.
• A datagram is basically an information but there is no guarantee of its content, arrival or
arrival time.
• Commonly used Constructors of DatagramSocket class
• DatagramSocket() throws SocketException: it creates a datagram socket and binds it with the
available Port Number on the localhost machine.
• DatagramSocket(int port) throws SocketException: it creates a datagram socket and binds it
with the given Port Number.
• DatagramSocket(int port, InetAddress address) throws SocketException: it creates a
datagram socket and binds it with the specified port number and host address.

45
• DatagramPacket class
• is a message that can be sent or received.
• If you send multiple packet, it may arrive in any order. Additionally, packet
delivery is not guaranteed.
• Commonly used Constructors of DatagramPacket class
• DatagramPacket(byte[] barr, int length): it creates a datagram packet. This
constructor is used to receive the packets.
• DatagramPacket(byte[] barr, int length, InetAddress address, int port): it
creates a datagram packet. This constructor is used to send the packets.

46
Example of Sending DatagramPacket
by DatagramSocket
import [Link].*;
public class DSender{
public static void main(String[] args) throws Exception {
DatagramSocket ds = new DatagramSocket();
String str = "Welcome java";
InetAddress ip = [Link]("[Link]");
DatagramPacket dp = new DatagramPacket([Link](),
[Link](), ip, 3000);
[Link](dp);
[Link]();
}
}

47
Example of Receiving
DatagramPacket by DatagramSocket
import [Link].*;
public class DReceiver{
public static void main(String[] args) throws Exception {
DatagramSocket ds = new DatagramSocket(3000);
byte[] buf = new byte[1024];
DatagramPacket dp = new DatagramPacket(buf, 1024);
[Link](dp);
String str = new String([Link](), 0, [Link]());
[Link](str);
[Link]();
}
}

48
URL
• The Web is a loose collection of higher-level protocols and file formats, all
unified in a web browser.
• Once you can reliably name anything and everything, it becomes a very
powerful paradigm. The Uniform Resource Locator (URL) does exactly that.
• The URL provides a reasonably intelligible form to uniquely identify or
address information on the Internet.
• URLs are ubiquitous; every browser uses them to identify information on the
Web.
• Within Java’s network class library, the URL class provides a simple, concise
API to access information across the Internet using URLs.

49
• Format
• A URL specification is based on four components:
• The first is the protocol to use, separated from the rest of the locator by a colon (:).
• The second component is the host name or IP address of the host to use; this is
delimited on the left by double slashes (//) and on the right by a slash (/) or
optionally a colon (:).
• The third component, the port number, is an optional parameter, delimited on the
left from the host name by a colon (:) and on the right by a slash (/).
• The fourth part is the actual file path.
• Java’s URL class has several constructors, and each can throw a
MalformedURLException.
• One commonly used form specifies the URL with a string that is identical to
what you see displayed in a browser:
• URL(String urlSpecifier)

50
• The next two forms of the constructor allow you to break up the URL into its
component parts:
• URL(String protocolName, String hostName, int port,
String path)
• URL(String protocolName, String hostName, String path)
• Another frequently used constructor allows you to use an existing URL as a
reference context and then create a new URL from that context.
• URL(URL urlObj, String urlSpecifier)

51
• Commonly used methods of Java URL class
• The [Link] class provides many methods. The important methods of
URL class are given below.
Method Description
• public String getProtocol() it returns the protocol of the
URL.
• public String getHost() it returns the host name of the
URL.
• public String getPort() it returns the Port Number of the
URL.
• public String getFile() it returns the file name of the
URL.
• public URLConnection it returns the instance of
openConnection() URLConnection i.e associated
with this URL.

52
• In the following example, we create a URL to SW web page and then examine its
properties:
import [Link].*;
class URLDemo {
public static void main(String args[]) throws
MalformedURLException {

URL hp = new URL(“


[Link]
[Link]("Protocol: " + [Link]());
[Link]("Port: " + [Link]());
[Link]("Host: " + [Link]());
[Link]("File: " + [Link]());
[Link]("Ext:" + [Link]());
}
}

53
• output:
• Protocol: http
• Port: -1
• Host: [Link]
• File: /[Link]/about-sw/
• Ext:[Link]

• To access the actual bits or content information of a URL, you create a


URLConnection object from it, using its openConnection( ) method,
like this:
• [Link]()

• openConnection( ) has the following general form:


• URLConnection openConnection( )

• It returns a URLConnection object associated with the invoking URL


object. It may throw an IOException.

54
URLConnection Class
• represents a communication link between the URL and the application.
• This class can be used to read and write data to the specified resource
referred by the URL.
• The openConnection() method of URL class returns the object of
URLConnection class.
• Syntax:
public URLConnection openConnection()throws IOException{}

• The URLConnection class provides many methods, we can display all


the data of a webpage by using the getInputStream() method.
• The getInputStream() method returns all the data of the specified URL
in the stream that can be read and displayed.

55
Example of Java URLConnecton class
import [Link].*;
import [Link].*;
public class URLConnectionExample {
public static void main(String[] args){
try{
URL url=new URL("[Link]
URLConnection urlcon=[Link]();
InputStream stream=[Link]();
int i;
while((i=[Link]())!=-1){
[Link]((char)i);
}
}catch(Exception e){[Link](e);}
}
}

56
HttpURLConnection class
• is http specific URLConnection. It works for HTTP protocol only.
• By the help of HttpURLConnection class, you can get information of any
HTTP URL such as header information, status code, response code etc.
• The [Link] is subclass of URLConnection class.
• How to get the object of HttpURLConnection class
• Get the URLConnection object using openConnection() method
• URLConnection openConnection(){}
• Typecast this object to HttpURLConnection type
• URL url=new URL("[Link]
• HttpURLConnection huc=(HttpURLConnection)[Link]();

57
HttpURLConnecton Example
import [Link].*;
import [Link].*;
public class HttpURLConnectionDemo{
public static void main(String[] args){
try{
URL url=new URL("[Link]
HttpURLConnection huc=(HttpURLConnection)[Link]();
for(int i=1;i<=8;i++){
[Link] ([Link](i) + " = " +
[Link](i));
}
[Link]();
}catch(Exception e){[Link](e);}
}
}

58
Serving Multiple Clients

▪ A server can serve multiple clients.


▪ The connection to each client is handled by one thread.
▪ Multiple clients are quite often connected to a single server at the same time.
▪ You can use threads to handle the server's multiple clients simultaneously.
▪ Simply create a thread for each connection.

59
Cont…
▪ Here is how the server handles the establishment of a
connection:

▪ 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.

60
Example: Serving Multiple Clients

Note: Start the server first, then start multiple clients.

61
Example: Serving Multiple

Clients
import [Link].*; import [Link].*; import [Link].*; import
[Link].*; import [Link].*;
public class MultiThreadServer extends JFrame {
// Text area for displaying contents private JTextArea jta = new
JTextArea();
public static void main(String[] args) {
new MultiThreadServer();
}
public MultiThreadServer() {
// Place text area on the frame
setLayout(new BorderLayout());
add(new JScrollPane(jta), [Link]);
setTitle("MultiThreadServer");
setSize(500, 300); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true); // It is necessary to show the frame here!
try {
// Create a server socket
ServerSocket serverSocket = new ServerSocket(8000);
[Link]("MultiThreadServer started at " + new Date() + '\n' );
// Number a client int clientNo = 1;

62
Example: Serving Multiple
• Clients
while (true) {
// Listen for a new connection request
Socket socket = [Link]();
// Display the client number
[Link]("Starting thread for client " + clientNo +
" at " + new Date() + '\n' );
// Find the client's host name and IP address InetAddress
inetAddress = [Link]();
[Link]("Client " + clientNo + "'s host name is “
+ [Link]() + "\n");
[Link]("Client " + clientNo + "'s IP Address is “
+ [Link]() + "\n");
// Create a new thread for the connection
HandleAClient task = new HandleAClient(socket);
// Start the new thread
new Thread(task).start();
// Increment clientNo
clientNo++;
}
}
catch(IOException ex) {
[Link](ex);
}
}

63
Example: Serving Multiple
Clients
// Inner class
// Define the thread class for handling new
connection class HandleAClient implements Runnable {
private Socket socket; // A connected socket
/** Construct a thread */
public HandleAClient(Socket socket) {
[Link] = socket;
}

@Override /** Run a thread */ public void run(){


try {
// Create data input and output streams
DataInputStream inputFromClient = new
DataInputStream([Link]()); DataOutputStream outputToClient =
new DataOutputStream([Link]());
// Continuously serve the client while (true) {
// Receive radius from the client
double radius = [Link]();
// Compute area
double area = radius * radius * [Link];
// Send area back to the client [Link](area);
[Link]("radius received from client: " + radius + '\n' );
[Link]("Area found: " + area + '\n' );
}
}
catch(IOException e) { [Link](e);
}
}
}
31

}
• You
Sending
can also
and Receiving Objects
send ObjectOutputStream on socket streams.

• A program can send and receive objects from


another program.
• In the preceding examples, you learned how to
send and receive data of primitive types.
and receive objects
using and
ObjectInputStream
• To enable passing, the objects must be
serializable.
• The following example demonstrates how to send
and receive objects. 65
Example: Passing Objects in Network
Programs

Write a program that Server Client


collects student student object student object

information from a
[Link]() [Link](student)
client and send them to
a server. Passing in: ObjectInputStream out: ObjectOutputStream
student information in
an object. [Link] [Link]

socket socket

Network

66
Example: Passing Objects in
Network Programs
public class StudentAddress implements [Link] {
private String name; private String street; private String city;
private String state; private String zip;
public StudentAddress(String name, String street, String city, String
state, String zip) {
[Link] = name; [Link] = street; [Link] = city; [Link]
= state; [Link] = zip;
}
public String getName() {
return name;
}
public String getStreet() {
return street; public return String getCity() {
}
city;

}
state; public return String getState() {
}

zip;
}
public return String getZip() {
34

}
Example: Passing Objects in
Network Programs
import [Link].*; import [Link].*; import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
public class StudentClient extends JApplet {
private JTextField jtfName = new JTextField(32);
private JTextField jtfStreet = new JTextField(32);
private JTextField jtfCity = new JTextField(20);
private JTextField jtfState = new JTextField(2);
private JTextField jtfZip = new JTextField(5);
// Button for sending a student's address to the server
private JButton jbtRegister = new JButton("Register to the Server");
// Indicate if it runs as application
private boolean isStandAlone = false;
// Host name or IP address String host = "localhost"; public void init() {
// Panel p1 for holding labels Name, Street, and City
JPanel p1 = new JPanel(); [Link](new GridLayout(3, 1)); [Link](new
JLabel("Name")); [Link](new JLabel("Street")); [Link](new
JLabel("City"));
35
Example: Passing Objects in Network Programs
// Panel jpState for holding state JPanel jpState = new
JPanel(); [Link](new BorderLayout());
[Link](new JLabel("State"),
[Link]);
[Link](jtfState, [Link]);
// Panel jpZip for holding zip
JPanel jpZip = new JPanel();
[Link](new BorderLayout()); [Link](new
JLabel("Zip"), [Link]); [Link](jtfZip,
[Link]);

// Panel p2 for holding jpState and jpZip JPanel p2 = new


JPanel(); [Link](new BorderLayout()); [Link](jpState,
[Link]); [Link](jpZip, [Link]);

// Panel p3 for holding jtfCity and p2 JPanel p3 = new JPanel();


[Link](new BorderLayout());

[Link](jtfCity,
[Link]);
36
Example: Passing Objects in
• Network Programs
[Link](p2, [Link]);
// Panel p4 for holding jtfName, jtfStreet, and p3
JPanel p4 = new JPanel(); [Link](new GridLayout(3, 1));
[Link](jtfName);
[Link](jtfStreet);
[Link](p3);
// Place p1 and p4 into StudentPanel
JPanel studentPanel = new JPanel(new BorderLayout());
[Link](new BevelBorder([Link]));
[Link](p1, [Link]);
[Link](p4, [Link]);
// Add the student panel and button to the applet
add(studentPanel, [Link]); add(jbtRegister,
[Link]);
// Register listener
[Link](new ButtonListener());
// Find the IP address of the Web server
if (!isStandAlone)
host = getCodeBase().getHost();
}
/** Handle button action */
private class ButtonListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
try {
// Establish connection with the server
Socket socket = new Socket(host, 8000);

70
Example: Passing Objects in
Network
// Create an Programs
output stream to the server
ObjectOutputStream toServer = new
ObjectOutputStream([Link]());
// Get text field
String name = [Link]().trim(); String
street = [Link]().trim(); String city =
[Link]().trim(); String state =
[Link]().trim(); String zip =
[Link]().trim();
// Create a StudentAddress object and send to the
server StudentAddress s =
new StudentAddress(name, street, city, state,
zip);
[Link](s);
}
catch (IOException ex) { [Link](ex);
}
}
}

71
Example: Passing Objects in
Network Programs
/** Run the applet as an application */ public static void main(String[]
args) {
// Create a frame
JFrame frame = new JFrame("Register Student Client");
// Create an instance of the applet StudentClient applet = new
StudentClient(); [Link] = true;
// Get host
if ([Link] == 1) [Link] = args[0];
// Add the applet instance to the frame
[Link](applet, [Link]);
// Invoke init() and start() [Link](); [Link]();
// Display the frame [Link](); [Link](true);
}
}

72
Example: Passing Objects in
Network Programs
• import [Link].*;
import [Link].*;
public class StudentServer {
private ObjectOutputStream outputToFile; private ObjectInputStream inputFromClient; public
static void main(String[] args) { new StudentServer();
}

public StudentServer() {
try {
// Create a server socket
ServerSocket serverSocket = new ServerSocket(8000); [Link]("Server started ");

// Create an object output stream


outputToFile = new ObjectOutputStream(
new FileOutputStream("[Link]", true));

while (true) {
// Listen for a new connection request
Socket socket = [Link]();

// Create an input stream from the socket inputFromClient = new


ObjectInputStream([Link]());

73
Example: Passing Objects in
// Network
Read from inputPrograms
Object object = [Link]();
// Write to the file [Link](object);
[Link]("A new student object is stored");
}
}
catch(ClassNotFoundException ex) { [Link]();
}
catch(IOException ex) { [Link]();
}
finally {
try { [Link](); [Link]();
}
catch (Exception ex) { [Link]();
}
}
}
}

74

You might also like