[go: up one dir, main page]

0% found this document useful (0 votes)
27 views71 pages

Chapter 4 Network Programming 2025

Chapter four discusses the fundamentals of network programming, focusing on how computers communicate over the Internet using protocols, IP addresses, and port numbers. It explains the roles of client and server in network interactions, as well as the Java networking classes and methods used for socket programming. The chapter also includes examples of client-server communication and the use of streams for data transmission.

Uploaded by

miki
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)
27 views71 pages

Chapter 4 Network Programming 2025

Chapter four discusses the fundamentals of network programming, focusing on how computers communicate over the Internet using protocols, IP addresses, and port numbers. It explains the roles of client and server in network interactions, as well as the Java networking classes and methods used for socket programming. The chapter also includes examples of client-server communication and the use of streams for data transmission.

Uploaded by

miki
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
You are on page 1/ 71

Chapter four :

Network Programming

1
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.
2
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.
– It is a logical address that can be changed.
– Every host on Internet has a unique IP address
– An IP address consists of four dotted decimal numbers ranging from
0 and 255, such as
143.89.40.46, 203.184.197.198
203.184.197.196, 203.184.197.197, 127.0.0.
– Since it is difficult to remember IP address, there is a special server
called Domain Name Server(DNS), which translates hostname to IP
address
– Example: DomainName: www.google.com, localhost
IPAddresess: 216.58.207.4 127.0.0.1
– One domain name can correspond to multiple internet addresses:
• www.yahoo.com:
66.218.70.49; 66.218.70.50; 66.218.71.80; 66.218.71.84; …
– Domain Naming Service (DNS) maps names to numbers
3
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. 4
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.

5
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
6
Client server communication
How Java handle such issues
Client
Request

Response
Client
Server
.
.
.
Client
7
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 java.net 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 java.net 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.

8
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
OutputStr InputStr
eam eam
Client Server

InputStr OutputStr 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 java.net.Socket class represents a socket, and


• The java.net.ServerSocket class provides a mechanism for the server program
to listen for clients and establish connections with them.
11
Client/Server Communications
The statements needed to create sockets on a server and a client
are shown below.

12
• 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.
13
• 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.
14
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 java.net.BindException.

15
Client Sockets
• After a server socket is created, the server can use the following
statement to listen for connections:
Socket socket = serverSocket.accept();
• 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.

16
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 130.254.204.33 at port 8000:

• Socket socket = new Socket("130.254.204.33", 8000)

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


as follows: 142.250.201.14

Socket socket = new Socket(“www.google.com", 8000);

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

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

18
Data Transmission through
Sockets

19
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 =socket.getInputStream();

OutputStream output = socket.getOutputStream();

20
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 (socket.getInputStream());
DataOutputStream output = new DataOutputStream
(socket.getOutputStream());

•The server can use input.readDouble() to receive a double value from the client, and
output.writeDouble(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. 21
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

22
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

socket.getInputStream socket.getOutputStream socket.getOutputStream socket.getOutputStream

socket socket socket socket

Network Network

(A) (B) 18
ServerSocket Class
• The java.net.ServerSocket 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 java.net.Socket 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.

27
Java Sockets

• Java wraps OS sockets (over TCP) by the objects of class java.net.Socket


• 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
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 java.net.*;
import java.io.*;
public class GreetingClient {
public static void main(String [] args) {
String serverName = args[0];
int port = Integer.parseInt(args[1]);
try {
System.out.println("Connecting to " +
serverName + " on port " + port);
Socket client = new Socket(serverName, port);
33
System.out.println("Just connected to " +
client.getRemoteSocketAddress());
OutputStream outToServer =
client.getOutputStream();
DataOutputStream out = new
DataOutputStream(outToServer);
out.writeUTF("Hello from " +
client.getLocalSocketAddress());
InputStream inFromServer =
client.getInputStream();
DataInputStream in = new
DataInputStream(inFromServer);
System.out.println("Server says " +
in.readUTF());
client.close();

}catch(IOException e) {
e.printStackTrace();

}
} }
34
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 java.net.*;
import java.io.*;
public class GreetingServer extends Thread {
private ServerSocket serverSocket;
public GreetingServer(int port) throws IOException {

serverSocket = new ServerSocket(port);


serverSocket.setSoTimeout(10000);
}
35
public void run() {
while(true) {
try {
System.out.println("Waiting for client on port " +
serverSocket.getLocalPort() + "...");
Socket server = serverSocket.accept();
System.out.println("Just connected to " +
server.getRemoteSocketAddress());
DataInputStream in = new
DataInputStream(server.getInputStream());
System.out.println(in.readUTF());
DataOutputStream out = new
DataOutputStream(server.getOutputStream());
out.writeUTF("Thank you for connecting to " +
server.getLocalSocketAddress() + "\nGoodbye!");
server.close();
36
}
catch(SocketTimeoutException s) {
System.out.println("Socket timed out!");
break;

}catch(IOException e) {
e.printStackTrace();
break;

}
}
}
public static void main(String [] args) {
int port = Integer.parseInt(args[0]);
try {
Thread t = new GreetingServer(port);
t.start();
}catch(IOException e) {
e.printStackTrace();
}}}
37
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 java.net package.
• Java supports UDP through the following two main classes from java.net:
• DatagramSocket Used to send and receive UDP packets.
• Acts like a mailbox for sending or receiving datagrams on a specific port.
• DatagramPacket Represents the actual data being sent or received.

39
import java.io.*; import java.net.*;
import java.io.*; import java.net.*;

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
System.out.println("UDP Server is running on port " + serverSocket.getLocalPort()); String message = "Hello, server!";
// create a byte array to hold incoming data byte[] sendData = message.getBytes();
byte[] receiveData = new byte[1024]; InetAddress serverAddress = InetAddress.getByName("localhost");

// create a DatagramPacket to receive incoming packets int serverPort = 1234;

DatagramPacket receivePacket = new DatagramPacket(receiveData, DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length,


serverAddress, serverPort); // create a DatagramPacket to send to the server
receiveData.length);
while (true) { // wait for incoming packets serverSocket.receive(receivePacket); clientSocket.send(sendPacket); // send the packet to the server
// extract the data from the packet System.out.println("Sent message: " + message + " to " + serverAddress + ":" +

UDP String message = new String(receivePacket.getData(), 0, receivePacket.getLength()); serverPort);


InetAddress clientAddress = receivePacket.getAddress(); byte[] receiveData = new byte[1024]; // create a byte array to hold the incoming
int clientPort = receivePacket.getPort(); System.out.println("Received message: " + message + " from " + data

SERVER
clientAddress + ":" + clientPort);
// create a DatagramPacket to receive the response from the server DatagramPacket
// send a response to the client receivePacket = new DatagramPacket(receiveData, receiveData.length);
String response = "Hello, client!"; // wait for the response from the server clientSocket.receive(receivePacket);
// extract the data from the packet
byte[] sendData = response.getBytes();
String response = new String(receivePacket.getData(), 0, receivePacket.getLength());
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, clientAddress,
clientPort); serverSocket.send(sendPacket); InetAddress server = receivePacket.getAddress();
System.out.println("Sent message: " + response + " to " + clientAddress + ":" + clientPort); int port = receivePacket.getPort(); System.out.println("Received message: " + response
+ " from " + server + ":" + port); // close the socket clientSocket.close();
} } catch (IOException e) {
} e.printStackTrace();
catch (IOException e) { }
e.printStackTrace(); }
}
}
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.

41
• 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.

42
Example of Sending DatagramPacket by
DatagramSocket
import java.net.*;
public class DSender{
public static void main(String[] args) throws Exception {
DatagramSocket ds = new DatagramSocket();
String str = "Welcome java";
InetAddress ip = InetAddress.getByName("127.0.0.1");
DatagramPacket dp = new DatagramPacket(str.getBytes(),
str.length(), ip, 3000);
ds.send(dp);
ds.close();

}
}
43
Example of Receiving DatagramPacket by
DatagramSocket
import java.net.*;
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);
ds.receive(dp);
String str = new String(dp.getData(), 0, dp.getLength());
System.out.println(str);
ds.close();
}
}
44
• start server as follows:
• $ java GreetingServer 6000

• Check client program as follows:


• $ java GreetingClient localhost 6000

45
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.
46
• 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)

47
• 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)

48
• Commonly used methods of Java URL class
• The java.net.URL 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. 49
• In the following example, we create a URL to SW web page and then examine its
properties:
import java.net.*;
class URLDemo {
public static void main(String args[]) throws
MalformedURLException {

URL hp = new URL(“


http://sw.aastu.edu.et/index.php/about-sw/");
System.out.println("Protocol: " + hp.getProtocol());
System.out.println("Port: " + hp.getPort());
System.out.println("Host: " + hp.getHost());
System.out.println("File: " + hp.getFile());
System.out.println("Ext:" + hp.toExternalForm());
}
50
}
• output:
• Protocol: http
• Port: -1
• Host: sw.aastu.edu.et
• File: /index.php/about-sw/
• Ext:http://sw.aastu.edu.et/index.php/about-sw/
• To access the actual bits or content information of a URL, you
create a URLConnection object from it, using its
openConnection( ) method, like this:
• url.openConnection()
• openConnection( ) has the following general form:
• URLConnection openConnection( )
• It returns a URLConnection object associated with the invoking
URL object. It may throw an IOException.
51
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.
52
Example of Java URLConnecton class
import java.io.*;
import java.net.*;
public class URLConnectionExample {
public static void main(String[] args){
try{
URL url=new URL("http://www.javatpoint.com/java-tutorial");
URLConnection urlcon=url.openConnection();
InputStream stream=urlcon.getInputStream();
int i;
while((i=stream.read())!=-1){
System.out.print((char)i);
}
}catch(Exception e){System.out.println(e);}
}
}
53
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 java.net.HttpURLConnection 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("http://www.javatpoint.com/java-tutorial");
• HttpURLConnection huc=(HttpURLConnection)url.openConnection();
54
HttpURLConnecton Example
import java.io.*;
import java.net.*;
public class HttpURLConnectionDemo{
public static void main(String[] args){
try{
URL url=new URL("http://sw.aastu.edu.et/");
HttpURLConnection huc=(HttpURLConnection)url.openConnection();
for(int i=1;i<=8;i++){
System.out.println (huc.getHeaderFieldKey(i) + " = " +
huc.getHeaderField(i));
}
huc.disconnect();
}catch(Exception e){System.out.println(e);}
}
}
55
56
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.
 Here is how the server handles the establishment of a connection:
while (true) {
Socket socket = serverSocket.accept(); Thread thread =
new ThreadClass(socket); thread.start();
}
 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.

57
Example: Serving Multiple Clients

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

58
Example: Serving Multiple Clients
• import java.io.*; import java.net.*; import java.util.*; import
java.awt.*; import javax.swing.*;
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), BorderLayout.CENTER);
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);
jta.append("MultiThreadServer started at " + new Date() + '\n' );
// Number a client int clientNo = 1;

59
Example: Serving Multiple Clients
• while (true) {
// Listen for a new connection request
Socket socket = serverSocket.accept();
// Display the client number
jta.append("Starting thread for client " + clientNo +
" at " + new Date() + '\n' );
// Find the client's host name and IP address InetAddress
inetAddress = socket.getInetAddress();
jta.append("Client " + clientNo + "'s host name is “
+ inetAddress.getHostName() + "\n");
jta.append("Client " + clientNo + "'s IP Address is “
+ inetAddress.getHostAddress() + "\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) {
System.err.println(ex);
}
}

60
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) {
this.socket = socket;
}

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


try {
// Create data input and output streams
DataInputStream inputFromClient = new
DataInputStream(socket.getInputStream()); DataOutputStream outputToClient =
new DataOutputStream(socket.getOutputStream());
// Continuously serve the client while (true) {
// Receive radius from the client
double radius = inputFromClient.readDouble();
// Compute area
double area = radius * radius * Math.PI;
// Send area back to the client outputToClient.writeDouble(area);
jta.append("radius received from client: " + radius + '\n' );
jta.append("Area found: " + area + '\n' );
}
}
catch(IOException e) { System.err.println(e);
}
}
}
31

}
Sending and Receiving Objects
• You can also 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. 62
Example: Passing Objects in Network
Programs

Write a program that Server Client


collects student student object student object

information from a
in.readObject() out.writeObject(student)
client and send them to
a server. Passing in: ObjectInputStream out: ObjectOutputStream
student information in
an object. socket.getInputStream socket.getOutputStream

socket socket

Network

63
Example: Passing Objects in Network
Programs
public class StudentAddress implements java.io.Serializable {
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) {
this.name = name; this.street = street; this.city = city; this.state
= state; this.zip = zip;
}
public String getName() {
return name;
}
public String getStreet() {
return street;
}
city;

state;
} publi String getCity() {
c
retur
zip;
} n
} 34
publi String getState() {
c
retur
n
publi String getZip() {
Example: Passing Objects in Network
import java.io.*;Programs
import java.net.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;
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(); p1.setLayout(new
Example: Passing Objects in Network Program
// Panel jpState for holding state JPanel
jpState = new JPanel(); jpState.setLayout(new
BorderLayout()); jpState.add(new
JLabel("State"),
BorderLayout.WEST);
jpState.add(jtfState, BorderLayout.CENTER);
// Panel jpZip for holding zip
JPanel jpZip = new JPanel();
jpZip.setLayout(new BorderLayout());
jpZip.add(new JLabel("Zip"),
BorderLayout.WEST); jpZip.add(jtfZip,
BorderLayout.CENTER);
// Panel p2 for holding jpState and jpZip
JPanel p2 = new JPanel(); p2.setLayout(new
BorderLayout()); p2.add(jpState,
BorderLayout.WEST); p2.add(jpZip,
BorderLayout.CENTER);
// Panel p3 for holding jtfCity and p2 JPanel
p3 = new JPanel(); p3.setLayout(new
p3.add(jtfCity,
BorderLayout()); 36
Example: Passing Objects in Network
• Programs
p3.add(p2, BorderLayout.EAST);
// Panel p4 for holding jtfName, jtfStreet, and p3
JPanel p4 = new JPanel(); p4.setLayout(new GridLayout(3, 1));
p4.add(jtfName);
p4.add(jtfStreet);
p4.add(p3);
// Place p1 and p4 into StudentPanel
JPanel studentPanel = new JPanel(new BorderLayout());
studentPanel.setBorder(new BevelBorder(BevelBorder.RAISED));
studentPanel.add(p1, BorderLayout.WEST);
studentPanel.add(p4, BorderLayout.CENTER);
// Add the student panel and button to the applet
add(studentPanel, BorderLayout.CENTER); add(jbtRegister,
BorderLayout.SOUTH);
// Register listener
jbtRegister.addActionListener(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);

67
Example: Passing Objects in Network
Programs
// Create an output stream to the server
ObjectOutputStream toServer = new
ObjectOutputStream(socket.getOutputStream());
// Get text field
String name = jtfName.getText().trim(); String
street = jtfStreet.getText().trim(); String city =
jtfCity.getText().trim(); String state =
jtfState.getText().trim(); String zip =
jtfZip.getText().trim();
// Create a StudentAddress object and send to the
server StudentAddress s =
new StudentAddress(name, street, city, state,
zip);
toServer.writeObject(s);
}
catch (IOException ex) { System.err.println(ex);
}
}
}

68
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(); applet.isStandAlone
= true;
// Get host
if (args.length == 1) applet.host =
args[0];
// Add the applet instance to the frame
frame.add(applet, BorderLayout.CENTER);
// Invoke init() and start()
applet.init(); applet.start();
// Display the frame frame.pack(); 69
Example: Passing Objects in Network
• Programs
import java.io.*;
import java.net.*;
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);
System.out.println("Server started
");
// Create an object output stream
outputToFile = new ObjectOutputStream(
new FileOutputStream("student.dat",
true));
while (true) { 70
Example: Passing Objects in Network
Programs
// Read from input
Object object =
inputFromClient.readObject();
// Write to the file
outputToFile.writeObject(object);
System.out.println("A new student object
is stored");
}
}
catch(ClassNotFoundException ex) {
ex.printStackTrace();
}
catch(IOException ex) {
ex.printStackTrace();
}
finally {
try { inputFromClient.close();
outputToFile.close();
}
catch (Exception ex) {
ex.printStackTrace();
} 71

You might also like