0% found this document useful (0 votes)
180 views40 pages

Chapter 14 (Networking)

Uploaded by

waim20214
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)
180 views40 pages

Chapter 14 (Networking)

Uploaded by

waim20214
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/ 40

CST(SS) -2205

Java 2 Enterprise Edition (J2EE)


Advanced Java Programming

©https://blogs.ashrithgn.com/
Reference Books

1. Java 2 (JDK 5 Edition) Programming Black Book (New/ 2006 Edition) by


Steven Holzner et al.
Chapter (14) Networking with Java
Chapter (31) Remote Method Invocation (RMI)

2. Java Server Programming (J2EE 1.4 Edition) Black Book (2006 Print) by
Steven Holzner et al.
Chapter (1) & (7) Introduction to J2EE and Web Containers
Chapter (8) Understanding Servlet Programming
Chapter (9) Understanding Servlet Sessions
Chapter (10) Understanding of Java Server Pages and JSTL
Chapter (6) JDBC and Database Programming

2 Faculty of Computer Science ©https://blogs.ashrithgn.com/


Chapter (14)
Networking with Java

Java 2 Black Book


(pp. 629 - 665)
Session-1

©https://blogs.ashrithgn.com/
Basic of Networking

 linking multiple devices so that they can readily share information and software
resources.
 Three elements in networking
 Client – sends request for services
 Server – sends response
 Network – media of communication

4 Faculty of Computer Science ©https://blogs.ashrithgn.com/


Client Server in Networking

 involves two types of programs: client and server.


 Server : a program that provides services to one or more clients.
 Client : a program that makes a service request from server.
 Example –› World Wide Web
Server : Web Server
Client : Web Browsers

What is protocol?
 Protocol is the special set of rules that end points in a telecommunication
connection use when they communicate.

5 Faculty of Computer Science ©https://blogs.ashrithgn.com/


Transmission Control Protocol (TCP)

 like a telephone call.


 a connection-based protocol, guarantees that data sent from one end of the
connection actually gets to the other end in the same order it was sent
 works together with Internet Protocol (IP)
 TCP/IP makes a reliable communication channel.
 Additional internet protocols:
 HTTP (Hypertext Transfer Protocol) pinterest.com
 FTP (File Transfer Protocol)

6 Faculty of Computer Science ©https://blogs.ashrithgn.com/


User Datagram Protocol (UDP)

 like a postal service


 a connection-less protocol
 It sends independent packets of data, called datagrams, from one application to
another.
 The order of delivery is not important and is not guaranteed, and each message
is independent of any other.

clipartmax.com

7 Faculty of Computer Science ©https://blogs.ashrithgn.com/


TCP vs.UDP

Ref: https://microchipdeveloper.com/tcpip:tcp-vs-udp
8 Faculty of Computer Science ©https://blogs.ashrithgn.com/
Port

 A computer port is a type of electronic, software- or programming-related


docking point through which information flows from a program on your
computer or to your computer from the Internet or another computer in a
network.

 Ports are numbered for consistency and programming.

 Ports are represented by a 16-bit number (0 to 65535)

9 Faculty of Computer Science ©https://blogs.ashrithgn.com/


Port(Cont’d)

 User level process/services generally use port number >=1024 (port number
<1024 are reserved for special services.)
 Some well known ports:
 ftp 21/tcp
 telnet 23/tcp
 smtp 25/tcp
 http 80/tcp

10 Faculty of Computer Science ©https://blogs.ashrithgn.com/


Internet Addressing and DNS

 Every computer on the internet has an address, called IP Address.


 This address is a number that uniquely identifies each computer on the net.
 Example addresses and their name:
Name Address
www.google.com 216.239.57.99
www.amazon.com 207.171.166.48
Name to Address Resolution is
DNS – Domain Name Server
done by DNS Server.
 DNS translates hostnames that humans can remember (like www.javapoint.com)
into numeric Internet addresses (like 52.89.84.245).

11 Faculty of Computer Science ©https://blogs.ashrithgn.com/


IP Address

 An Internet Protocol address (IP address) is a numerical label assigned to


each device (e.g., computer, printer) participating in a computer network.
 IP addresses are binary numbers, but they are usually stored in text files and
displayed in human-readable notations, such as 172.16.254.1 (for IPv4), and
2001:db8:0:1234:0:567:8:1 (for IPv6).

12 Faculty of Computer Science ©https://blogs.ashrithgn.com/


URL Class

 Stands for Universal/Uniform Resource Locator


 based on four components:
 The protocol (http, ftp, etc.)
 Host name or IP address
 Port number (optional)
 The actual file path

https://www.oracle.com/java/technologies/javase/training-support.html
Protocol Domain
File path

13 Faculty of Computer Science ©https://blogs.ashrithgn.com/


URI Class

 stands for Uniform Resource Identifier.


 Every URL is a URI, but not every URI is a URL.
 There is another subcategory of URIs, Uniform Resource Names (URNs),
which name resources but do not specify how to locate them.

14 Faculty of Computer Science ©https://blogs.ashrithgn.com/


Assignment

Describe the followings:

 Inet4Address vs. Inet6Address


 Syntax and components of URI class

15 Faculty of Computer Science ©https://blogs.ashrithgn.com/


Java Net API

 Provides the classes for implementing networking applications.


 Some classes in java.net package:

import java.net.*; Java.net Package


InetAddress
Socket
ServerSocket
URI
URL
DatagramPacket
DatagramSocket

16 Faculty of Computer Science ©https://blogs.ashrithgn.com/


InetAddress Class

 represents an IP address
 provides methods to get the IP of any host name and vice versa
 two types of address:
 Unicast - sends IP packets to a single recipient on a network
 Multicast - sends IP packets to a group of hosts on a network

17 Faculty of Computer Science ©https://blogs.ashrithgn.com/


InetAddress Class(Cont’d)

 Some methods of InetAddress class:


 String getHostAddress()
 String getHostName()
 static InetAddress getLocalHost()
 static InetAddress getByName(String host)
 static InetAddress[] getAllByName(String host)
 static InetAddress getByAddress(String host, byte[] addr)
 boolean isLoopbackAddress()
 Boolean isMulticastAddress()

18 Faculty of Computer Science ©https://blogs.ashrithgn.com/


Example:InetAddress Class

import java.net.*;
public class InetAddressEg {
public static void main(String[] args) {
try {
System.out.println(InetAddress.getLocalHost());
String name="www.google.com";
System.out.println(InetAddress.getByName(name));
InetAddress[] addresses=InetAddress.getAllByName(name);
for(InetAddress address:addresses){
System.out.println(address); 130-42VN/172.20.10.5
} www.google.com/74.125.68.103
} catch (UnknownHostException e) { www.google.com/74.125.68.103
e.printStackTrace();} www.google.com/74.125.68.99
} www.google.com/74.125.68.105
} www.google.com/74.125.68.106
www.google.com/74.125.68.104
www.google.com/74.125.68.147

19 Faculty of Computer Science ©https://blogs.ashrithgn.com/


Java Socket Programming

 is used for communication between the applications running on the network.


 connection-oriented socket programming
 Socket and ServerSocket classes are used

 connection-less socket programming


 DatagramSocket and DatagramPacket classes

20 Faculty of Computer Science ©https://blogs.ashrithgn.com/


Socket Class

 is simply an endpoint for communications between the machines


 is used to create a socket
 Some constructors
 Socket()
 Socket(InetAddress address, int port)
 Socket(String host, int port)

21 Faculty of Computer Science ©https://blogs.ashrithgn.com/


Socket Class(Cont’d)

 Some Methods

Method Description
1) public InputStream getInputStream() returns the InputStream attached
with this socket.
2) public OutputStream getOutputStream() returns the OutputStream attached
with this socket.
3) public void close() closes this socket

22 Faculty of Computer Science ©https://blogs.ashrithgn.com/


ServerSocket Class

 Can be used to create a server socket.


 Create object that is used to establish communication with the clients.
 Constructors
 ServerSocket()
 ServerSocket(int port)
 ServerSocket(int port, int maxQueue)
 ServerSocket(int port, int maxQueue,InetAddress localAddress)

23 Faculty of Computer Science ©https://blogs.ashrithgn.com/


ServerSocket Class(Cont’d)

 Some Methods

Method Description
1)public Socket accept() returns the socket and establish a connection
between server and client.
2) public void close() closes the server socket.

24 Faculty of Computer Science ©https://blogs.ashrithgn.com/


Socket Programming in Java

Creating Server
 need to create the instance of ServerSocket class
 ServerSocket ss=new ServerSocket(port number);

ServerSocket ss=new ServerSocket(9999);


Socket s=ss.accept();//establishes connection and waits for the client

Creating Client
 need to create the instance of Socket class
 Socket s=new Socket(“Server Name”, PortNumber);

Socket s=new Socket("localhost",9999);

25 Faculty of Computer Science ©https://blogs.ashrithgn.com/


Socket Programming in Java (Cont’d)

Read data form Client or Server

DataInputStream in = new DataInputStream (socket.getInputStream());


in.readInt();
in.readUTF();

Write data to Client or Server

DataOutputStream out =new DataOutputStream(socket.getOutputStream());


out.writeInt();
out.writeUTF();

26 Faculty of Computer Science ©https://blogs.ashrithgn.com/


Socket Programming in Java (Cont’d)

Read data form Console


1. BufferedReader br = new BufferedReader (new InputStreamReader (System.in))
2. Scanner sc=new Scanner(System.in)

27 Faculty of Computer Science ©https://blogs.ashrithgn.com/


Example-1

 Server
- Receives a text
- Prints it

 Client
- Sends a text

28 Faculty of Computer Science ©https://blogs.ashrithgn.com/


Example1: Server Program

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


public class MyServer {
public static void main(String[] args){
try{
ServerSocket ss=new ServerSocket(9999);
System.out.println("Server is Ready");
Socket s=ss.accept(); System.out.println(“Connection is established");
DataInputStream din=new DataInputStream(s.getInputStream());
String str=din.readUTF();
System.out.println("message= "+str);
ss.close();
}catch(Exception e){System.out.println(e);}
} }
29 Faculty of Computer Science ©https://blogs.ashrithgn.com/
Example1: Client Program

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


public class MyClient {
public static void main(String[] args) {
try{
Socket s=new Socket("localhost",9999);
DataOutputStream dout=new DataOutputStream(s.getOutputStream());
dout.writeUTF("Hello Server");
dout.close();
s.close();
}catch(Exception e){System.out.println(e);}
}
}

30 Faculty of Computer Science ©https://blogs.ashrithgn.com/


Example2:Calculator Program

 Server
- acts as a calculator
- accepts command and inputs, and calculates them
- returns result

 Client
- interacts with user to get inputs
- request the server giving command with data
- receive the result

31 Faculty of Computer Science ©https://blogs.ashrithgn.com/


Example2: Server Program

import java.io.*;
import java.net.*;
public class CalculatorServer {
String cmd = "";
int num1 = 0;
int num2 = 0;
int result = 0;
public CalculatorServer() throws IOException {
ServerSocket svrSocket = new ServerSocket(1025);
System.out.println("Server is ready***");
Socket connSocket = svrSocket.accept();
System.out.println("Server and client is connected");
32 Faculty of Computer Science ©https://blogs.ashrithgn.com/
Example2: Server Program(Cont’d)

while (true)
{
// create inputStream object to read data form client
DataInputStream in = new DataInputStream(connSocket.getInputStream());
cmd = in.readUTF();
num1 = in.readInt();
num2 = in.readInt();
// method call associate with command from user
if (cmd.equalsIgnoreCase("ADD")) {
result =calculateSum(num1, num2);
} else if (cmd.equalsIgnoreCase("SUB")) {
result =calculateSub(num1, num2);
}

33 Faculty of Computer Science ©https://blogs.ashrithgn.com/


Example2: Server Program(Cont’d)

else if (cmd.equalsIgnoreCase("MULT")) {
result = calculateMultiply(num1, num2);
} else {
result = calculateDivide(num1, num2);
}
DataOutputStream out = new DataOutputStream(
connSocket.getOutputStream());
out.writeInt(result);
svrSocket.close();
}
}
// calculate methods
private int calculateSum(int n1, int n2) {
return (n1 + n2);
34 } Faculty of Computer Science ©https://blogs.ashrithgn.com/
Example2: Server Program(Cont’d)

private int calculateSub(int n1, int n2) {


return n1 - n2;
}
private int calculateMultiply(int n1, int n2) {
return n1 * n2;
}
private int calculateDivide(int n1, int n2) {
return n1 / n2;
}
public static void main(String[] args) throws IOException {

new CalculatorServer();
}
}
35 Faculty of Computer Science ©https://blogs.ashrithgn.com/
Example2: Client Program

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.*;
public class CalculatorClient {
char ch;
public CalculatorClient() throws IOException,UnknownHostException{
Socket cliSocket = new Socket("localhost", 1025);
do {
// create inputStream object
BufferedReader br = new BufferedReader(new InputStreamReader(
System.in));
36 Faculty of Computer Science ©https://blogs.ashrithgn.com/
Example2: Client Program(Cont’d)

// read user input


System.out.println("Type a command ( ADD, SUB,MULT,DIV): ");
String cmd = br.readLine();
System.out.println("Enter number1 :");
int num1 = Integer.parseInt(br.readLine());
System.out.println("Enter number2 :");
int num2 = Integer.parseInt(br.readLine());
// create outputStream object
DataOutputStream out = new DataOutputStream(cliSocket.getOutputStream());
// send data to server
out.writeUTF(cmd);
out.writeInt(num1);
out.writeInt(num2);

37 Faculty of Computer Science ©https://blogs.ashrithgn.com/


Example2: Client Program(Cont’d)

// creating inputStream to read server reply


DataInputStream in = new DataInputStream(cliSocket.getInputStream());
int result = in.readInt();
System.out.println("Result = " + result);
System.out.println("Try it more (y/n): ");
ch = br.readLine().toLowerCase().charAt(0);
} while (ch == 'y');

cliSocket.close();
}
public static void main(String[] args) throws IOException {
new CalculatorClient();
}
}
38 Faculty of Computer Science ©https://blogs.ashrithgn.com/
Exercise

Write a client server program to calculate the Area and Perimeter of a Square.
Client accepts the length and sends it to the server. The server calculates and returns
the results. Client should display these results.

39 Faculty of Computer Science ©https://blogs.ashrithgn.com/


40 Faculty of Computer Science ©https://blogs.ashrithgn.com/

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy