0% found this document useful (0 votes)
14 views15 pages

ch3 Networking

Uploaded by

dorarali369
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)
14 views15 pages

ch3 Networking

Uploaded by

dorarali369
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/ 15

COURSE NAME : ADVANCED OBJECT ORIENTED

PROGRAMMING
COURSE CODE : 223CCS-3

CHAPTER 3: NETWORKING
SUBJECT COORDINATOR: MRS. MARIYAM AYSHA BIVI
SUBJECT TEACHERS: MR. OMER BIN HUSSAIN
MS. SHUMUKH HUSSAIN
DEPARTMENT OF COMPUTER SCIENCE
KING KHALID UNIVERSITY
ABHA, KSA.

Chapter No TOPICS Page Number Book Reference


Networking Basics 1168-1169
TEXT BOOK 2: JAVA:
The Networking Classes and 1170-1171
Interfaces The Complete
Identifying the System 1171-1173 Reference– Eleventh
TCP/IP Client Sockets 1173-1177 Edition, by Herbert
3 Schildt, 2019,
URL 1178-1180
McGraw-Hill
URL connection 1180-1184
Education (Publisher).
TCP/IP Server Sockets 1187-1188 Chapter 23
Simulating a Client Server – Refer Class Notes &
Architecture http://www.lms.kku.edu.sa
CHAPTER 3 : NETWORKING

 Networking Basics
 The Networking Classes and Interfaces

 Identifying the System

 URL

 URL connection

 TCP/IP Client Sockets

 TCP/IP Server Sockets

 Simulating a Client Server – Architecture

2
3.1 NETWORKING BASICS
 Java’s networking support is the concept of a socket.
 A socket identifies an endpoint in a network. socket allows a single computer to
serve many different clients at once, as well as to serve many different types of
information. This is accomplished through the use of a port, which is a numbered
socket on a particular machine.
 A server process is said to "listen" to a port until a client connects to it.
 A server is allowed to accept multiple clients connected to the same port number
 Socket communication takes place via a protocol.
 Internet Protocol (IP) : low-level routing protocol that breaks data into small
packets and sends them to an address across a network, which does not
guarantee to deliver said packets to the destination.
 Transmission Control Protocol (TCP) : higher-level protocol that manages to
robustly string together these packets, sorting and retransmitting them as
necessary to reliably transmit data.
 User Datagram Protocol (UDP) : sits next to TCP and can be used directly to
support fast, connectionless, unreliable transport of packets. 3
 Hyper Text Transfer protocol(HTTP): The protocol that web browsers and
servers use to transfer hyper-text pages and images
3.2 THE NETWORKING CLASSES AND INTERFACES
 The java.net package provides the classes that support socket-based client/server
communication
 Java supports both the TCP and UDP protocol families
 Some of java.net package classes:
 InetAddress

 URL

 URLConnection

 Socket

 ServerSocket

 DatagramSocket

 DatagramPacket

 Socket

 ServerSocket

 SocketAddress

 Inet4Address 4

 Inet6Address (Refer Text Book 3 Page Number 1170)


3.3 IDENTIFYING THE SYSTEM (INETADDRESS)
 The InetAddress class is used to encapsulate both the numerical IP address and the
domain name for that address
 Internet address is a number that uniquely identifies each computer on the Net.
 IPv4((Internet Protocol, version 4): consist of 32-bit values, organized as four 8-bit
values.
 IPv6(Internet Protocol, version 6) :uses a 128-bit values, organized into eight 16-bit
chunks, which supports a much larger address space.
 Domain name : name of an Internet address, describes a machine’s location in a name
space. example, www.HerbSchildt.com
 Domain Naming Service (DNS) : An Internet domain name is mapped to an IP address by
DNS. users work with domain names, but the Internet operates on IP addresses.
 To create an InetAddress object we have to use one of the available factory methods:
static InetAddress getLocalHost( ) returns the InetAddress object that
throws UnknownHostException represents the local host
static InetAddress getByName (String hostName) returns an InetAddress
throws UnknownHostException for a host name passed to it
static InetAddress[ ] getAllByName(String hostName) returns an array of InetAddresses that5
throws UnknownHostException represent all of the addresses that a
particular name resolves to.
3.3 IDENTIFYING THE SYSTEM (INETADDRESS) (CONT…)
PROGRAM 1: P1_Demo_InetAddress.java OUTPUT OF PROGRAM 1:
import java.net.*; Local Machine Details
DESKTOP-IS5PRBS/192.168.100.37
class P1_Demo_InetAddress {
public static void main (String[] args) throws www.kku.edu.sa Details
UnknownHostException{ www.kku.edu.sa/212.26.68.64
InetAddress ia = InetAddress.getLocalHost();
System.out.println("Local Machine Details"); www.youtube.com Details
System.out.println(ia); www.youtube.com/216.58.211.206

www.youtube.com All Details


ia = InetAddress.getByName("www.kku.edu.sa");
www.youtube.com/216.58.211.206
System.out.println("\nwww.kku.edu.sa Details"); www.youtube.com/142.251.37.46
System.out.println(ia); www.youtube.com/142.251.37.174
www.youtube.com/142.251.37.206
ia = InetAddress.getByName("www.youtube.com"); www.youtube.com/142.251.37.238
System.out.println("\nwww.youtube.com Details"); www.youtube.com/142.250.200.206
www.youtube.com/142.250.200.238
System.out.println(ia);
www.youtube.com/142.250.201.14
www.youtube.com/142.250.201.46
InetAddress ias[] = www.youtube.com/142.250.203.238
InetAddress.getAllByName("www.youtube.com"); www.youtube.com/172.217.171.238
System.out.println("\nwww.youtube.com All Details"); www.youtube.com/172.217.21.14
for(int i=0; i<ias.length; i++) www.youtube.com/2a00:1450:4006:800:0:0:0:200e
System.out.println(ias[i]); www.youtube.com/2a00:1450:4006:80d:0:0:0:200e
www.youtube.com/2a00:1450:4006:80e:0:0:0:200e
www.youtube.com/2a00:1450:4006:80f:0:0:0:200e
}
6
} Process completed.
3.4 URL(UNIFORM RESOURCE LOCATOR)
 URL uniquely identify or address information on the Internet.
 URL class provides a simple API to access information across the Internet using URLs
http://www.google.com:80/index.htm

Protocol identifier Host name or IP Address Port Number file path


 Several constructors throwing MalformedURLException:
 URL(String urlSpecifier)
 URL(String protocolName, String hostName, int port, String path)
 URL(String protocolName, String hostName, String path)
 URL(URL urlObj, String urlSpecifier) throws MalformedURLException

 To access the actual bits or content information of a URL, create a URLConnection object
from it, using its openConnection( ) method, like this:
urlc = url.openConnection()
 openConnection( ) has the following general form:
URLConnection openConnection( ) throws IOException 7
3.4 URL (CONT..)
PROGRAM 2: P2_URL_Demo.java
import java.net.*;
class P2_URL_Demo { OUTPUT OF PROGRAM 2:
public static void main (String[] args) throws MalformedURLException { Protocol : http
URL u1 = new URL("http://www.kku.edu.sa:80/index.html"); Host Name : www.kku.edu.sa
System.out.println("Protocol : "+u1.getProtocol()); Port Number : 80
// Protocol : http File Name : /index.html
System.out.println("Host Name : "+u1.getHost()); Ext : http://www.kku.edu.sa:80/index.html
// Host Name : www.kku.edu.sa Protocol : http
System.out.println("Port Number : "+u1.getPort()); / Host Name : www.kku.edu.sa
// Port Number : 80
Port Number : 80
System.out.println("File Name : "+u1.getPath());
File Name : index.html
// File Name : /index.html
Ext : http://www.kku.edu.sa:80index.html
System.out.println("Ext : "+u1.toExternalForm());
Protocol : http
// Ext : http://www.kku.edu.sa:80/index.html
Host Name : www.kku.edu.sa
Port Number : -1
URL u2 = new URL("http","www.kku.edu.sa",80,"index.html");
File Name : index.html
System.out.println("Protocol : "+u2.getProtocol()); // Protocol : http
Ext : http://www.kku.edu.saindex.html
System.out.println("Host Name : "+u2.getHost());
// Host Name : www.kku.edu.sa
Process completed.
System.out.println("Port Number : "+u2.getPort()); // Port Number : 80
System.out.println("File Name : "+u2.getPath()); // File Name : /index.html
System.out.println("Ext : "+u2.toExternalForm()); // Ext
If the port is –1; this means that a port
was not explicitly set.
URL u3 = new URL("http","www.kku.edu.sa","index.html");
System.out.println("Protocol : "+u3.getProtocol()); // Protocol : http
System.out.println("Host Name : "+u3.getHost());
// Host Name : www.kku.edu.sa
8
System.out.println("Port Number : "+u3.getPort()); // Prot Number : 80
System.out.println("File Name : "+u3.getPath()); // File Name : /index.html
System.out.println("Ext : "+u3.toExternalForm()); // Ext
} }
3.5 URL CONNECTION
 URLConnection is a general-purpose class for accessing the attributes of a remote
resource.
 Once a connection to a remote server is made, URLConnection can be used to inspect the
properties of the remote object before actually transporting it locally.
 These attributes are exposed by the HTTP protocol specification
 URLConnection defines several methods.
 Int getContentLengthLong()
 Sting getContentType()
 Long getDate()
 Long getExpiration()
 Long getLastModified()
 InputStream getInputStream() throws IOException

(Refer Text Book 3 Page Number 1181)

9
3.5 URL CONNECTION (CONT..)
PROGRAM 3: P3_URLConnection_Demo.java
// Demonstrate URLConnection.
import java.net.*; OUTPUT OF PROGRAM 3:
import java.io.*; Date: Thu Oct 19 00:05:58 AST 2023
import java.util.Date; Content-Type: text/html
class P3_URLConnection_Demo { No expiration information.
public static void main(String args[]) throws Exception No last-modified information.
{ Content-Length: 8
int c; === Content ===
URL hp = new URL("http://www.yahoo.com"); redirect
URLConnection hpCon = hp.openConnection(); // get date Process completed.
long d = hpCon.getDate();
if(d==0) System.out.println("No date information.");
else System.out.println("Date: " + new Date(d)); // get content type
System.out.println("Content-Type: " + hpCon.getContentType());
d = hpCon.getExpiration(); // get expiration date
if (d==0) System.out.println("No expiration information.");
else System.out.println("Expires: " + new Date(d)); //get last-modified date
d = hpCon.getLastModified();
if (d==0) System.out.println("No last-modified information.");
else System.out.println("Last-Modified: " + new Date(d)); //get content length
long len = hpCon.getContentLengthLong();
if(len == -1) System.out.println("Content length unavailable.");
else System.out.println("Content-Length: " + len);
if(len != 0)
{ System.out.println("=== Content ===");
InputStream input = hpCon.getInputStream();
while (((c = input.read()) != -1)) 10
{ System.out.print((char) c);
} input.close();
} else { System.out.println("No content available.");
} } }
3.6 TCP/IP CLIENT SOCKETS
 TCP/IP sockets are used to implement reliable, bidirectional, persistent, pointto-point,
stream-based connections between hosts on the Internet.
 A socket can be used to connect Java’s I/O system to other programs that may reside
either on the local machine or on any other machine on the Internet.
 Two kinds of TCP sockets in java.net package :
 ServerSocket class: for servers, designed to be a “listener” which waits for clients to
connect before doing anything.
 Socket class: for clients, designed to connect to server socket and initiate protocol
exchanges
 The creation of a Socket object establishes a connection between the client and server.
 Two constructors used to create client sockets:

 Some Methods of Client Socket are:


connect( )  which allows you to specify a new connection;
isConnected( )  which returns true if the socket is connected to a server;
isBound( )  which returns true if the socket is bound to an address; 11
isClosed( )  which returns true if the socket is closed.
close( ) To close a socket.
3.7 TCP/IP SERVER SOCKETS
 The ServerSocket class is used to create servers that listen for either local or remote
client programs to connect to them on published ports.
 When ServerSocket, is created it will register itself with the system as having an interest
in client connections.
 The constructors for ServerSocket reflect the port number that you want to accept
connections on and, optionally, how long you want the queue for said port to be. The
queue length tells the system how many client connections it can leave pending before
it should simply refuse connections. The default is 50.
 Three Constructors used to create Server sockets:

 Methods of Server Socket is:


accept( )  which is a blocking call that will wait for a client to initiate 12
communications and then return with a normal Socket that is then
used for communication with the client.
3.8 SIMULATING A CLIENT SERVER – ARCHITECTURE
PROGRAM 4A: Simple_Server1.java PROGRAM 4B: Simple_Client1.java
import java.net.*; import java.net.*;
import java.io.*; import java.io.*;
import java.util.*; import java.util.*;

class SimpleServer1 { class SimpleClient1 {


public static void main (String[] args) throws Exception{ public static void main (String[] args) throws Exception {
ServerSocket ss = new ServerSocket(6790); Socket s = new Socket("localhost", 6790);
System.out.println("Server is Running...");
System.out.println("Server is waiting for the Client to be PrintWriter pw = new
Connected."); PrintWriter(s.getOutputStream(), true);
Socket s = ss.accept(); Scanner sc = new Scanner(System.in);
System.out.println("Client Connection Established"); String str;

Scanner sc = new Scanner(s.getInputStream()); System.out.print("Enter a Message : ");


String str; str = sc.nextLine();
str = sc.nextLine();
System.out.println("Message from Client : "+str); pw.println(str);

sc.close(); pw.close();
s.close(); s.close();
} }
} }

OUTPUT OF PROGRAM 4A: OUTPUT OF PROGRAM 4B:


Server is Running... Enter a Message : WELCOME
Server is waiting for the Client to be Connected. Process completed. 13
Client Connection Established
Message from Client : WELCOME
Process completed.
3.8 SIMULATING A CLIENT SERVER ARCHITECTURE(CONT..)
PROGRAM 5A: MyEchoServer.java PROGRAM 5B: MyEchoClient.java
import java.net.*; import java.net.*;
import java.io.*; import java.io.*;
import java.util.*; import java.util.*;

class MyEchoServer { class MyEchoClient {


public static void main (String[] args) throws Exception { public static void main (String[] args) throws Exception {
ServerSocket ss = new ServerSocket(3456); Socket s = new Socket("localhost", 3456);
Scanner sc = new Scanner(s.getInputStream());
System.out.println("MyEchoServer is Running..."); PrintWriter pw = new PrintWriter(s.getOutputStream(), true);
System.out.println("Waiting for the Client to be connected"); Scanner in = new Scanner(System.in);
String msg,str="";
Socket s = ss.accept(); while(!str.equals("STOP")) {
System.out.println("Client Connection Established"); System.out.print("Enter a message(Press STOP to Cancel
Scanner sc = new Scanner(s.getInputStream()); Echoing : ");
PrintWriter pw = new PrintWriter(s.getOutputStream(), str = in.nextLine();
true); pw.println(str); // sending the message to the Server
String msg, str=""; msg = sc.nextLine();
while(!str.equals("STOP")) { System.out.println(msg);
str = sc.nextLine(); // reading the message from the client }
msg = "Echo::"+str; s.close();
pw.println(msg); }
} }
s.close(); OUTPUT OF PROGRAM 5B:
} Enter a message(Press STOP to Cancel Echoing : HELLO
} Echo::HELLO
OUTPUT OF PROGRAM 5A: Enter a message(Press STOP to Cancel Echoing : ALL 14
MyEchoServer is Running... Echo::ALL
Waiting for the Client to be connected Enter a message(Press STOP to Cancel Echoing : STOP
Client Connection Established Echo::STOP
Process completed. Process completed.
3.8 SIMULATING A CLIENT SERVER ARCHITECTURE(CONT..)
PROGRAM 6A: EOServer.java
import java.net.*; PROGRAM 6B: EOClient.java
import java.io.*; import java.net.*;
import java.util.*; import java.io.*;
class EOServer { import java.util.*;
public static void main (String[] args) throws Exception { class EOClient {
ServerSocket ss = new ServerSocket(1234); public static void main (String[] args) throws Exception{
System.out.println("EOServer is Running"); Socket s = new Socket("localhost", 1234);
System.out.println("Waiting for Client..."); Scanner sc = new Scanner(s.getInputStream());
Socket s = ss.accept(); PrintWriter pw = new PrintWriter(s.getOutputStream(), true);
System.out.println("Client CONNECTED"); Scanner in = new Scanner(System.in);
Scanner sc = new Scanner(s.getInputStream()); String str;
String str = sc.nextLine(); int n=1;
int n = Integer.parseInt(str);
while(n != 0){ while(n != 0){
if(n % 2 == 0) System.out.print("Enter an int number(0 to Stop) :
");
System.out.println(n+" is a EVEN number");
str = in.nextLine();
else
n = Integer.parseInt(str);
System.out.println(n+" is a ODD number");
pw.println(str);
str = sc.nextLine();
}
n = Integer.parseInt(str);
s.close();
}
}
s.close();
}OUTPUT OF PROGRAM 6B:
} }
Enter an int number(0 to Stop) : 4
OUTPUT OF PROGRAM 6A: Enter an int number(0 to Stop) : 11
EOServer is Running
Enter an int number(0 to Stop) : 20
Waiting for Client...
Client CONNECTED
Enter an int number(0 to Stop) : 0 15
4 is a EVEN number
Process completed.
11 is a ODD number
20 is a EVEN number

You might also like