+ All Categories
Home > Education > Advance Java-Network Programming

Advance Java-Network Programming

Date post: 15-Jul-2015
Category:
Upload: ashok-hirpara
View: 220 times
Download: 0 times
Share this document with a friend
27
Network Programming in Java JAVA.NET PACKAGE PROVIDE CLASSES FOR NETWORK PROGRAMMING BY((ASHOK HIRPARA))
Transcript

Network

Programming

in JavaJAVA.NET PACKAGE PROVIDE CLASSES FOR NETWORK PROGRAMMING

BY((ASHOK HIRPARA))

Network Programming in

Java

Java’s network support

Addressing other machines

Communicating using TCP/IP

Communicating using UDP

Broadcasting and multicasting

Network Programming in

Java

Java distinguishes between UDP, TCP server & TCP

client sockets

java.net.InetAddress class represents a single

IP address

java.net.UnkownHostException thrown if DNS

system can’t find IP address for specific host

IP Addresses and Java

Java has a class java.net.InetAddress

which abstracts network addresses

Serves three main purposes:

Encapsulates an address

Performs name lookup (converting a host name into

an IP address)

Performs reverse lookup (converting the address

into a host name)

java.net.InetAddress

Static construction using a factory method

InetAddress getByName(String hostName)

hostName can be “host.domain.com.au”, or

hostName can be “130.95.72.134”

InetAddress getLocalHost()

Some useful methods:

String getHostName()

Gives you the host name (for example “www.sun.com”)

String getHostAddress()

Gives you the address (for example “192.18.97.241”)

InetAddress getLocalHost()

InetAddress[] getAllByName(String hostName)

Using InetAddress objects

import java.net.InetAddress;

import java.net.UnknownHostExcepion;

public static void main(String[] args)

{

try {

InetAddress inet1 =

InetAddress.getByName("asp.ee.uwa.edu.au");

System.out.println(

"HostAddress=" + inet1.getHostAddress());

InetAddress inet2 =

InetAddress.getByName("130.95.72.134");

System.out.println("HostName=" + inet2.getHostName());

if (inet1.equals(inet2))

System.out.println("Addresses are equal");

}

catch (UnknownHostException uhe) {

uhe.printStackTrace();

}

}

Transmission Control Protocol

TCP is built on top of IP

Provides the illusion of a continuous flow (or

stream) of data between sender and receiver (rather like a telephone call)

Splits up streams into strings of small datagrams

which are sent in succession

Contains an error recovery mechanism to recover

datagrams which are lost

These features make application development simpler and so it is widely used

Two types of TCP Socket

java.net.ServerSocket is used by servers

so that they can accept incoming TCP/IP

connections

A server is a piece of software which advertises and

then provides some service on request

java.net.Socket is used by clients who wish

to establish a connection to a (remote) server

A client is a piece of software (usually on a different

machine) which makes use of some service

java.net.ServerSocket

Listens on well-known port for incoming

connections

Creates a dynamically allocated port for each newly established connection

Provides a Socket connected to the new port

Maintains a queue to ensure that prospective

clients are not lost

java.net.ServerSocket

Construction:

ServerSocket(int port, int backlog)

Allows up to backlog requests to queue waiting for the server to deal with them

Some useful methods:

Socket accept()

Blocks waiting for a client to attempt to establish a connection

void close()

Called by the server when it is shutting down to ensure that any resources are deallocated

java.net.Socket

Provides access to TCP/IP streams

Bi-directional communication between sender

and receiver

Can be used to connect to a remote address

and port by using the constructor:

Socket(String remoteHost, int port)

Also used to accept an incoming connection

(see ServerSocket)

java.net.Socket

Can obtain access to input and output streams

Input stream allows reception of data from the

other party

InputSteam getInputStream()

Output stream allows dispatch of data to the

other party

OutputStream getOutputStream()

How it all fits together

2037 80

2037 1583

2037 1583

Client (A) Server (B)

ServerSocket ss.s = ss.accept()

s = new Socket(“B”, 80)

Socket s

s.getInputStream()s.getOuputStream()

s.getInputStream()s.getOuputStream()

A sample TCP server

public static void main(String[] args)

{

try {

ServerSocket agreedPort =

new ServerSocket(AGREED_PORT_NUMBER, 5);

while (isStillServing()) {

Socket session = agreedPort.accept();

respond(session);

session.close();

}

agreedPort.close();

}

catch (UnknownHostException uhe) {

// Very unlikely to occur

}

catch (IOException ioe) {

// May occur if the client misbehaves?

}

}

A sample TCP client

public static void main(String[] args)

{

try {

InetAddress server = InetAddress.getByName(args[0]);

Socket connection =

new Socket(server, AGREED_PORT_NUMBER);

makeRequestToServer(connection);

getReplyFromServer(connection);

connection.close();

}

catch (UnknownHostException uhe) {

// arg[0] is not a valid server name or IP address

}

catch (IOException ioe) {

// The connection to the server failed somehow:

// the server might have crashed mid sentence?

}

}

What are datagrams?

Datagrams are discrete packets of data

Each is like a parcel that can be addressed and

sent to an recipient anywhere on the Internet

This is abstracted as the User Datagram Protocol

(UDP) in RFC768 (August 1980)

Most networks cannot guarantee reliable delivery

of datagrams

Why use datagrams?

Good for sending data that can naturally be

divided into small chunks

Poor for (lossless) stream based communications

Makes economical use of network bandwidth (up

to 3 times the efficiency of TCP/IP for small

messages)

Datagrams can be locally broadcast or multicast

(one-to-many communication)

Application using

datagrams

UDP can be used for economical point-to-point

communications over LANs

Datagrams can be used for one-to-many

communication:

Local network broadcasting;

Multicasting (MBONE)

but there is no way to create one-to-many

streams using TCP/IP

java.net.DatagramPacket

(1)

DatagramPackets normally used as short lived

envelopes for datagram messages:

Used to assemble messages before they are

dispatched onto the network,

or dismantle messages after they have been

received

Has the following attributes:

Destination/source address

Destination/source port number

Data bytes constituting the message

Length of message data bytes

java.net.DatagramPacket

(2) Construction:

DatagramPacket(byte[] data, int length)

Some useful methods:

void setAddress(InetAddress addr)

InetAddress getAddress()

void setPort(int port)

int getPort()

DatagramPackets are not immutable so, in principle you can reuse then, but . .

Experience has shown that they often misbehave when you do -- create a new one, use it once, throw it away!

java.net.DatagramSocket

(1)

Used to represent a socket associated with a

specific port on the local host

Used to send or receive datagrams

Note: there is no counterpart to

java.net.ServerSocket! Just use a

DatagramSocket with a agreed port number so

others know which address and port to send their

datagrams to

java.net.DatagramSocket

(2) Construction:

DatagramSocket(int port)

Uses a specified port (used for receiving datagrams)

DatagramSocket()

Allocate any available port number (for sending)

Some useful methods:

void send(DatagramPacket fullPacket)

Sends the full datagram out onto the network

void receive(DatagramPacket emptyPacket)

Waits until a datagram and fills in emptyPacket with the message

. . . and a few more in the Javadoc

sea.datagram.DatagramSend

er

This example sends datagrams to a specific host (anywhere on the Internet)

The steps are as follows:

Create a new DatagramPacket

Put some data which constitutes your message in the new DatagramPacket

Set a destination address and port so that the network knows where to deliver the datagram

Create a socket with a dynamically allocated port number (if you are just sending from it)

Send the packet through the socket onto the network

sea.datagram.DatagramSen

derbyte[] data = “This is the message”.getBytes();

DatagramPacket packet =

new DatagramPacket(data, data.length);

// Create an address

InetAddress destAddress =

InetAddress.getByName(“fred.domain.com”);

packet.setAddress(destAddress);

packet.setPort(9876);

DatagramSocket socket = new DatagramSocket();

socket.send(packet);

sea.datagram.DatagramRecei

ver

The steps are the reserve of sending:

Create an empty DatagramPacket (and allocate a

buffer for the incoming data)

Create a DatagramSocket on an agreed socket

number to provide access to arrivals

Use the socket to receive the datagram (the thread

will block until a new datagram arrrives)

Extract the data bytes which make up the message

sea.datagram.DatagramRecei

ver// Create an empty packet with some buffer space

byte[] data = new byte[1500];

DatagramPacket packet =

new DatagramPacket(data, data.length);

DatagramSocket socket = new DatagramSocket(9876);

// This call will block until a datagram arrives

socket.receive(packet);

// Convert the bytes back into a String and print

String message =

new String(packet.getData(), 0, packet.getLength());

System.out.println("message is " + message);

System.out.println("from " + packet.getAddress());

But it’s never quite that

simple!

Several of the constructors/methods throw

exceptions which I have omitted

Each datagrams can only hold up to a maximum of 64KB of data . .

. . but the underlying transport layer may split the

message into smaller packets (for instance

Ethernet uses about 1500 bytes)

Always remember that UDP is an unreliable

protocol: If any of the split datagrams are lost the

whole message will be lost


Recommended