Top Banner
Networking with Java Carl Gunter ( gunter@cis ) Arvind Easwaran ( arvinde@saul ) Michael May ( mjmay@saul )
115

Networking with Java Carl Gunter ( gunter@cis ) Arvind Easwaran ( arvinde@saul ) Michael May ( mjmay@saul )

Jan 05, 2016

Download

Documents

Quentin Edwards
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Networking with Java Carl Gunter ( gunter@cis ) Arvind Easwaran ( arvinde@saul ) Michael May ( mjmay@saul )

Networking with Java

Carl Gunter ( gunter@cis )

Arvind Easwaran ( arvinde@saul )

Michael May ( mjmay@saul )

Page 2: Networking with Java Carl Gunter ( gunter@cis ) Arvind Easwaran ( arvinde@saul ) Michael May ( mjmay@saul )

Basics OOP, I/O, Exceptions

Threads Sockets

Connection oriented Connectionless

Cryptography API Security API JCA (JCE)

Topics

Page 3: Networking with Java Carl Gunter ( gunter@cis ) Arvind Easwaran ( arvinde@saul ) Michael May ( mjmay@saul )

Java Basics

Page 4: Networking with Java Carl Gunter ( gunter@cis ) Arvind Easwaran ( arvinde@saul ) Michael May ( mjmay@saul )

Data encapsulation Inheritance

Simple Multiple

Polymorphism Parametric Sub type

Information hiding Objects and Classes

OOP

Page 5: Networking with Java Carl Gunter ( gunter@cis ) Arvind Easwaran ( arvinde@saul ) Michael May ( mjmay@saul )

Objects and Classes Class Abstract entity

representing structure Consists of declarations/definitions for

variables and methods Object Instance of a class

Consists of actual data and methods that operate on them

Many instances of the same class The real data structure on which

operations are performed

Page 6: Networking with Java Carl Gunter ( gunter@cis ) Arvind Easwaran ( arvinde@saul ) Michael May ( mjmay@saul )

Java Classes

Java programs are a collection of class declarations

One class in each file with the file having the same name as the class

Each class defines a collection of data and function members

Page 7: Networking with Java Carl Gunter ( gunter@cis ) Arvind Easwaran ( arvinde@saul ) Michael May ( mjmay@saul )

Object in Java – A Class ! All classes in Java are descendants

of the class Object Class descendency

Trace back through the inheritance chain

All chains lead to the class Object Object class is default inheritance

when not specified

Page 8: Networking with Java Carl Gunter ( gunter@cis ) Arvind Easwaran ( arvinde@saul ) Michael May ( mjmay@saul )

Java Package

Archival of portable objects for reuse Similar to a “library” Steps for making/using a package

Make an object “public” Add “package” statement to object definition Compile object source code (compiler will store

compiled code according to package statement)

Import object into other code via “import” statement

Page 9: Networking with Java Carl Gunter ( gunter@cis ) Arvind Easwaran ( arvinde@saul ) Michael May ( mjmay@saul )

Packages Methods are grouped within classes A class is declared to be part of a package using the package

keyword Classes are imported using the import keyword

package srd.math;

public class ComplexNumber{ private double m_dReal; private double m_dImag;

// constructors public ComplexNumber(double dR, double dI){ m_dReal = dR; m_dImag = dI; }

Page 10: Networking with Java Carl Gunter ( gunter@cis ) Arvind Easwaran ( arvinde@saul ) Michael May ( mjmay@saul )

Class and MethodAccess Control Modifiers

Access ControlModifier

Class or InterfaceAccessibility

Member (Field or Method)Accessibility

Public All All if class or interface isaccessible; interface membersalways public

Protected N/A Same package OR subclass

“default”(Package private)

Same package Same package

Private N/A Only same class (notsubclass)

Page 11: Networking with Java Carl Gunter ( gunter@cis ) Arvind Easwaran ( arvinde@saul ) Michael May ( mjmay@saul )

Constructors

A method for creating an instance of a class Same name as class it is contained in “NO” return type or return values Instance variable initialization can be done here At least one public constructor in every class Constructors (and all methods) can be

overloaded Default constructor is always a “no argument” No default constructor is provided if the

programmer supplies at least one

Page 12: Networking with Java Carl Gunter ( gunter@cis ) Arvind Easwaran ( arvinde@saul ) Michael May ( mjmay@saul )

Constants using Final

NO change in value through the lifetime of the variable

Similar to the const keyword in C Variables declared with final

Can be initialized in a constructor, but must be assigned a value in every constructor of the class

Page 13: Networking with Java Carl Gunter ( gunter@cis ) Arvind Easwaran ( arvinde@saul ) Michael May ( mjmay@saul )

Building Composite Objects

Objects with objects as instance variables

Building up complex classes is good object oriented design Reuse of existing classes To detect bugs incrementally Debugging with test drivers as

classes are developed

Page 14: Networking with Java Carl Gunter ( gunter@cis ) Arvind Easwaran ( arvinde@saul ) Michael May ( mjmay@saul )

Symbolic Constants No global constants in Java Static members of a class give similar

functionality Examples:

public final static float PI = 3.1415926;where “final indicates this value cannot be altered

Static variable identifier can be a class if PI definition above is contained in class

Math, it can be referenced as Math.PI

Page 15: Networking with Java Carl Gunter ( gunter@cis ) Arvind Easwaran ( arvinde@saul ) Michael May ( mjmay@saul )

Static Initializers Sometimes a static data member needs to be initialized too

class BankAccount{ static private int m_nNextAccountNumber = 100001;}

Sometimes initialization requires more steps

class TelephoneConnection{ static final int m_nNUMBERCHANNELS = 64; static Channel[] m_channel;}

Java provides a special construct for this purpose

class TelephoneConnection{ static final int m_nNUMBERCHANNELS = 64; static Channel[] m_channel;

static{ for (int i = 0; i < m_nNUMBERCHANNELS; i++){ m_channel[i] = new Channel(i); } } }

Page 16: Networking with Java Carl Gunter ( gunter@cis ) Arvind Easwaran ( arvinde@saul ) Michael May ( mjmay@saul )

Class extension - Inheritance Classes can be defined as extensions

(subclasses) of already-defined classes Inherits methods,variables from the parent May contain additional attribute fields May provide additional functionality by

providing new methods May provide replacement functionality by

overriding methods in the superclass Often, a subclass constructor executes the

parent constructor by invoking super(…)

Page 17: Networking with Java Carl Gunter ( gunter@cis ) Arvind Easwaran ( arvinde@saul ) Michael May ( mjmay@saul )

Overloading methods void fn(TV mytv, Radio myradio){ mytv.ChangeChannel(); // tune the TV myradio.ChangeChannel(); // tune the radio } Current class assumed when no qualification Overloading based on different types of arguments

double fn(BankAccount baMyAccount){ baMyAccount.Rate(8.0); // sets the rate return baMyAccount.Rate(); // queries the rate }

No overloading based on return value

Page 18: Networking with Java Carl Gunter ( gunter@cis ) Arvind Easwaran ( arvinde@saul ) Michael May ( mjmay@saul )

this keyword A class declaration is like a template for

making objects The code is shared by all objects of the

class Each object has its own values for the data

members The object itself is an implicit parameter

to each method In the class declarations, one can use

the keyword “this” to refer to the object itself explicitly

Page 19: Networking with Java Carl Gunter ( gunter@cis ) Arvind Easwaran ( arvinde@saul ) Michael May ( mjmay@saul )

Java I/O - Streams All modern I/O is stream-based A stream is a connection to a source

of data or to a destination for data (sometimes both)

Different streams have different characteristics A file has a definite length, and

therefore an end Keyboard input has no specific end

Page 20: Networking with Java Carl Gunter ( gunter@cis ) Arvind Easwaran ( arvinde@saul ) Michael May ( mjmay@saul )

How to do I/O

import java.io.*;

Open the stream Use the stream (read, write, or

both) Close the stream

Page 21: Networking with Java Carl Gunter ( gunter@cis ) Arvind Easwaran ( arvinde@saul ) Michael May ( mjmay@saul )

Why Java I/O is hard

Java I/O is very powerful, with an overwhelming number of options

Any given kind of I/O is not particularly difficult Buffered Formatted etc

The trick is to find your way through the maze of possibilities

It’s all about picking the right one

Page 22: Networking with Java Carl Gunter ( gunter@cis ) Arvind Easwaran ( arvinde@saul ) Michael May ( mjmay@saul )

Opening a stream When you open a stream, you are

making a connection to an external entity

The entity to which you wish to write data to or read data from

Streams encapsulate complexity of external entity

Streams also provide flexibility in usage of data – Different types

Page 23: Networking with Java Carl Gunter ( gunter@cis ) Arvind Easwaran ( arvinde@saul ) Michael May ( mjmay@saul )

Example - Opening a stream

A FileReader is a used to connect to a file that will be used for input FileReader fileReader =

new FileReader(fileName); The fileName specifies where the

(external) file is to be found You never use fileName again;

instead, you use fileReader

Page 24: Networking with Java Carl Gunter ( gunter@cis ) Arvind Easwaran ( arvinde@saul ) Michael May ( mjmay@saul )

Using a stream

Some streams can be used only for input, others only for output, still others for both

Using a stream means doing input from it or output to it

But it’s not usually that simple One needs to manipulate the data in

some way as it comes in or goes out

Page 25: Networking with Java Carl Gunter ( gunter@cis ) Arvind Easwaran ( arvinde@saul ) Michael May ( mjmay@saul )

Example of using a stream int ch;

ch = fileReader.read( ); The fileReader.read() method reads one

character and returns it as an integer, or -1 if there are no more characters to read (EOF)

The meaning of the integer depends on the file encoding (ASCII, Unicode, other)

Page 26: Networking with Java Carl Gunter ( gunter@cis ) Arvind Easwaran ( arvinde@saul ) Michael May ( mjmay@saul )

Closing A stream is an expensive resource There is a limit on the number of streams

that you can have open at one time You should not have more than one

stream open on the same file You must close a stream before you can

open it again Always close your streams!

Page 27: Networking with Java Carl Gunter ( gunter@cis ) Arvind Easwaran ( arvinde@saul ) Michael May ( mjmay@saul )

Serialization

You can also read and write objects to files

Object I/O goes by the awkward name of serialization

Serialization can be very difficult objects may contain references to other

objects Java makes serialization (almost) easy

Page 28: Networking with Java Carl Gunter ( gunter@cis ) Arvind Easwaran ( arvinde@saul ) Michael May ( mjmay@saul )

Conditions for serializability

If an object is to be serialized The class must be declared as public Class must implement Serializable The class must have a no-argument

constructor All fields of the class must be

serializable Either primitive types or serializable

objects

Page 29: Networking with Java Carl Gunter ( gunter@cis ) Arvind Easwaran ( arvinde@saul ) Michael May ( mjmay@saul )

Exceptions Historically, programs would provide a

message and halt on errors Hardly acceptable in today’s interactive

environment In Java, methods “throw” exceptions

when such errors occur Method which invoked the method

encountering the error can either “catch” the exception, or pass it up the heirarchy

Page 30: Networking with Java Carl Gunter ( gunter@cis ) Arvind Easwaran ( arvinde@saul ) Michael May ( mjmay@saul )

General exception handling

If you write code including methods from which an exception may be thrown, here is an outline of what to dotry

{ < suspect code > }catch (Exception e) { < action to take > }

Page 31: Networking with Java Carl Gunter ( gunter@cis ) Arvind Easwaran ( arvinde@saul ) Michael May ( mjmay@saul )

Exception Example package srd.math;

import java.lang.Exception;

public class ComplexNumber{ // ... other data and methods as before

// division operator written to use exceptions public ComplexNumber Divide(double d) throws Exception{ if (d == 0.0){ throw new Exception("Divide by zero in ComplexNumber.divide"); } return new ComplexNumber(m_dReal / d, m_dImag / d); }}

Page 32: Networking with Java Carl Gunter ( gunter@cis ) Arvind Easwaran ( arvinde@saul ) Michael May ( mjmay@saul )

Java Threads

Page 33: Networking with Java Carl Gunter ( gunter@cis ) Arvind Easwaran ( arvinde@saul ) Michael May ( mjmay@saul )

Multitasking v/s Multithreading

Multitasking refers to a computer's ability to perform multiple jobs concurrently

A thread is a single sequence of execution within a program

Multithreading refers to multiple threads of control within a single program each program can run multiple threads of

control within it

Page 34: Networking with Java Carl Gunter ( gunter@cis ) Arvind Easwaran ( arvinde@saul ) Michael May ( mjmay@saul )

Threads - Need

To maintain responsiveness of an application during a long running task

To enable cancellation of separable tasks

Some problems are intrinsically parallel

Some APIs and systems demand it Swings Animation

Page 35: Networking with Java Carl Gunter ( gunter@cis ) Arvind Easwaran ( arvinde@saul ) Michael May ( mjmay@saul )

Example - Animation

Suppose you set up Buttons and attach Listeners to those buttons

Then your code goes into a loop doing the animation

Who’s listening ? Not this code; it’s busy doing the

animation sleep(ms) doesn’t help!

Page 36: Networking with Java Carl Gunter ( gunter@cis ) Arvind Easwaran ( arvinde@saul ) Michael May ( mjmay@saul )

Application Thread

When we execute an application The JVM creates a Thread object

whose task is defined by the main() method

It starts the thread The thread executes the statements

of the program one by one until the method returns and the thread dies

Page 37: Networking with Java Carl Gunter ( gunter@cis ) Arvind Easwaran ( arvinde@saul ) Michael May ( mjmay@saul )

Multiple Threads Each thread has its private run-time stack If two threads execute the same method,

each will have its own copy of the local variables the methods uses

All threads see the same dynamic memory, heap

Two different threads can act on the same object and same static fields concurrently Race conditions Deadlocks

Page 38: Networking with Java Carl Gunter ( gunter@cis ) Arvind Easwaran ( arvinde@saul ) Michael May ( mjmay@saul )

Creating Threads

There are two ways to create our own Thread object

1. Sub classing the Thread class and instantiating a new object of that class

2. Implementing the Runnable interface In both cases the run() method

should be implemented

Page 39: Networking with Java Carl Gunter ( gunter@cis ) Arvind Easwaran ( arvinde@saul ) Michael May ( mjmay@saul )

Example – Sub classpublic class ThreadExample extends Thread {

public void run () {

for (int i = 1; i <= 100; i++) {

System.out.println(“Thread: ” + i);

} } }

Page 40: Networking with Java Carl Gunter ( gunter@cis ) Arvind Easwaran ( arvinde@saul ) Michael May ( mjmay@saul )

Thread Methods

void start() Creates new thread and makes it runnable This method can be called only once

void run() The new thread begins its life inside this

method

void stop() The thread is being terminated

Page 41: Networking with Java Carl Gunter ( gunter@cis ) Arvind Easwaran ( arvinde@saul ) Michael May ( mjmay@saul )

Thread Methods (Continued)

yield() Causes currently executing thread object to

temporarily pause and allow other threads to execute

Allows only threads of the same priority to run

sleep(int m)/sleep(int m,int n)   The thread sleeps for m milliseconds, plus n

nanoseconds

Page 42: Networking with Java Carl Gunter ( gunter@cis ) Arvind Easwaran ( arvinde@saul ) Michael May ( mjmay@saul )

Example - Implementing Runnable

public class RunnableExample implements Runnable {

public void run () {

for (int i = 1; i <= 100; i++) {

System.out.println (“Runnable: ” + i);

} } }

Page 43: Networking with Java Carl Gunter ( gunter@cis ) Arvind Easwaran ( arvinde@saul ) Michael May ( mjmay@saul )

Why two mechanisms ?

Java supports simple inheritance A class can have only one super

class But it can implement many

interfaces Allows threads to run , regardless

of inheritanceExample – an applet that is also a thread

Page 44: Networking with Java Carl Gunter ( gunter@cis ) Arvind Easwaran ( arvinde@saul ) Michael May ( mjmay@saul )

Starting the Threads

public class ThreadsStartExample {

public static void main (String argv[]) {

new ThreadExample ().start ();

new Thread(new RunnableExample ()).start ();

} }

Page 45: Networking with Java Carl Gunter ( gunter@cis ) Arvind Easwaran ( arvinde@saul ) Michael May ( mjmay@saul )

Scheduling Threads

I/O operation completes

start()

Currently executedthread

Ready queue

Newly createdthreads

Page 46: Networking with Java Carl Gunter ( gunter@cis ) Arvind Easwaran ( arvinde@saul ) Michael May ( mjmay@saul )

Alive

Thread State Diagram

New Thread Dead Thread

Running

Runnable

new ThreadExample();

run() method returns

while (…) { … }

Blocked Object.wait()Thread.sleep()blocking IO callwaiting on a monitor

thread.start();

Page 47: Networking with Java Carl Gunter ( gunter@cis ) Arvind Easwaran ( arvinde@saul ) Michael May ( mjmay@saul )

Example

public class PrintThread1 extends Thread {

String name;

public PrintThread1(String name) {

this.name = name; }

public void run() {

for (int i=1; i<500 ; i++) {

try {

sleep((long)(Math.random() * 100));

} catch (InterruptedException ie) { }

System.out.print(name); } }

Page 48: Networking with Java Carl Gunter ( gunter@cis ) Arvind Easwaran ( arvinde@saul ) Michael May ( mjmay@saul )

Example (cont)

public static void main(String args[]) {

PrintThread1 a = new PrintThread1("*");

PrintThread1 b = new PrintThread1("-");

PrintThread1 c = new PrintThread1("=");

a.start();

b.start();

c.start();

} }

Page 49: Networking with Java Carl Gunter ( gunter@cis ) Arvind Easwaran ( arvinde@saul ) Michael May ( mjmay@saul )

Scheduling

Thread scheduling is the mechanism used to determine how runnable threads are allocated CPU time

Priority is taken into consideration Thread-scheduling mechanisms

preemptive or nonpreemptive

Page 50: Networking with Java Carl Gunter ( gunter@cis ) Arvind Easwaran ( arvinde@saul ) Michael May ( mjmay@saul )

Preemptive Scheduling Preemptive scheduling

Scheduler preempts a running thread to allow different threads to execute

Nonpreemptive scheduling Scheduler never interrupts a running thread

The nonpreemptive scheduler relies on the running thread to yield control of the CPU so that other threads may execute

Page 51: Networking with Java Carl Gunter ( gunter@cis ) Arvind Easwaran ( arvinde@saul ) Michael May ( mjmay@saul )

Java Scheduling Scheduler is preemptive and based on priority

of threads Uses fixed-priority scheduling

Threads are scheduled according to their priority w.r.t. other threads in the ready queue

The highest priority runnable thread is always selected for execution

When multiple threads have equally high priorities, only one of those threads is guaranteed to be executing

Java threads are guaranteed to be preemptive but not time sliced

Page 52: Networking with Java Carl Gunter ( gunter@cis ) Arvind Easwaran ( arvinde@saul ) Michael May ( mjmay@saul )

Thread Priority Every thread has a priority When a thread is created, it inherits

the priority of the thread that created it

The priority values range from 1 to 10, in increasing priority

The priority can be adjusted using setPriority() and getPriority() methods

Pre defined priority constants MIN_PRIORITY=1 MAX_PRIORITY=10 NORM_PRIORITY=5

Page 53: Networking with Java Carl Gunter ( gunter@cis ) Arvind Easwaran ( arvinde@saul ) Michael May ( mjmay@saul )

ThreadGroup

The ThreadGroup class is used to create groups of similar threads. Why is this needed?

“Thread groups are best viewed as an unsuccessful experiment, and you may simply ignore their existence.”

Joshua Bloch, software architect at Sun

Page 54: Networking with Java Carl Gunter ( gunter@cis ) Arvind Easwaran ( arvinde@saul ) Michael May ( mjmay@saul )

Race Condition

Race conditions Outcome of a program is affected by the

order in which the program's threads are allocated CPU time

Two threads are simultaneously modifying a single object

Both threads “race” to store their value Outcome depends on which one wins the

“race”

Page 55: Networking with Java Carl Gunter ( gunter@cis ) Arvind Easwaran ( arvinde@saul ) Michael May ( mjmay@saul )

Monitors Each object has a “monitor” that is a

token used to determine which application thread has control of a particular object instance

In execution of a synchronized method (or block), access to the object monitor must be gained before the execution Synchronized method – Method that executes

critical section Access to the object monitor is queued This avoids “Race Conditions”

Page 56: Networking with Java Carl Gunter ( gunter@cis ) Arvind Easwaran ( arvinde@saul ) Michael May ( mjmay@saul )

Example

public class BankAccount {

private float balance;

public synchronized void deposit(float amount) {

balance += amount;} public synchronized void withdraw(float

amount) { balance -= amount;} }

Page 57: Networking with Java Carl Gunter ( gunter@cis ) Arvind Easwaran ( arvinde@saul ) Michael May ( mjmay@saul )

Static Synchronized Methods

Marking a static method as synchronized, associates a monitor with the class itself

The execution of synchronized static methods of the same class is mutually exclusive. Why?

Page 58: Networking with Java Carl Gunter ( gunter@cis ) Arvind Easwaran ( arvinde@saul ) Michael May ( mjmay@saul )

Example

public class PrintThread2 extends Thread {

String name;

public PrintThread2(String name) {

this.name = name; }

public static synchronized void print(String name) {

for (int i=1; i<500 ; i++) {

try {

Thread.sleep((long)(Math.random() * 100));

} catch (InterruptedException ie) { }

System.out.print(str); } }

Page 59: Networking with Java Carl Gunter ( gunter@cis ) Arvind Easwaran ( arvinde@saul ) Michael May ( mjmay@saul )

Example (cont)

public void run() {

print(name); }

public static void main(String args[]) {

PrintThread2 a = new PrintThread2("*“);

PrintThread2 b = new PrintThread2("-“);

PrintThread2 c = new PrintThread2("=“);

a.start();

b.start();

c.start(); } }

Page 60: Networking with Java Carl Gunter ( gunter@cis ) Arvind Easwaran ( arvinde@saul ) Michael May ( mjmay@saul )

Synchronized Statements A monitor can be assigned to a block It can be used to monitor access to a data

element that is not an object, e.g., array Example:

void arrayShift(byte[] array, int count) {

synchronized(array) {

System.arraycopy (array, count,array,

0, array.size - count); } }

Page 61: Networking with Java Carl Gunter ( gunter@cis ) Arvind Easwaran ( arvinde@saul ) Michael May ( mjmay@saul )

The wait() Method The wait() method is part of the

java.lang.Object interface It requires a lock on the object’s

monitor to execute It must be called from a

synchronized method, or from a synchronized segment of code Why?

Page 62: Networking with Java Carl Gunter ( gunter@cis ) Arvind Easwaran ( arvinde@saul ) Michael May ( mjmay@saul )

The wait() Method

wait() causes the current thread to wait until another thread invokes the notify() method or the notifyAll() method for this object

Upon call for wait(), the thread releases ownership of this monitor and waits until another thread notifies the waiting threads of the object

Page 63: Networking with Java Carl Gunter ( gunter@cis ) Arvind Easwaran ( arvinde@saul ) Michael May ( mjmay@saul )

The wait() Method

wait() is also similar to yield() Both take the current thread off the

execution stack and force it to be rescheduled

However, wait() is not automatically put back into the scheduler queue notify() must be called in order to get a

thread back into the scheduler’s queue

Page 64: Networking with Java Carl Gunter ( gunter@cis ) Arvind Easwaran ( arvinde@saul ) Michael May ( mjmay@saul )

Things Thread should NOT do

The Thread controls its own destiny Deprecated methods

myThread.stop( ) myThread.suspend( ) myThread.resume( )

Outside control turned out to be a Bad Idea

Don’t do this!

Page 65: Networking with Java Carl Gunter ( gunter@cis ) Arvind Easwaran ( arvinde@saul ) Michael May ( mjmay@saul )

Controlling another Thread

Don’t use the deprecated methods! Instead, put a request where the

other Thread can find it boolean okToRun = true;

animation.start( ); public void run( ) {

while (controller.okToRun) {…}

Page 66: Networking with Java Carl Gunter ( gunter@cis ) Arvind Easwaran ( arvinde@saul ) Michael May ( mjmay@saul )

Java Sockets

Page 67: Networking with Java Carl Gunter ( gunter@cis ) Arvind Easwaran ( arvinde@saul ) Michael May ( mjmay@saul )

Why Java Sockets ?

Why use sockets to communicate with remote objects when RMI is available? To communicate with non-java objects and

programs Not all software on networks is written in Java

To communicate as efficiently as possible Convenience of RPC and RMI extract a price in

the form of processing overhead  A well-designed socket interface between

programs can outperform them       

Page 68: Networking with Java Carl Gunter ( gunter@cis ) Arvind Easwaran ( arvinde@saul ) Michael May ( mjmay@saul )

What Is a Socket ? Server side

Server has a socket bound to a specific port number The server just waits, listening to the socket for a client to make a

connection request If everything goes well, the server accepts the connection Upon acceptance, the server gets a new socket bound to a

different port Client-side

The client knows the hostname of the machine on which the server is running and the port number to which the server is connected

To make a connection request, the client tries to rendezvous with the server on the server's machine and port

if the connection is accepted, a socket is successfully created and the client can use the socket to communicate with the server

The client and server can now communicate by writing to or reading from their sockets.  

Page 69: Networking with Java Carl Gunter ( gunter@cis ) Arvind Easwaran ( arvinde@saul ) Michael May ( mjmay@saul )

Socket Communication There are two forms of socket communication, connection

oriented and connectionless TCP (Transmission Control Protocol)

TCP is a connection oriented, transport layer protocol that works on top of IP

Provides a permanent connection oriented virtual circuit Circuit has to be established before data transfer can

begin The client will send out a send a number of initialization

packets to the server so that the circuit path through the network can be established

A host will usually establish two streams, one for incoming and one for out going data

Other mechanisms to ensure that data integrity is maintained

Packets are numbered to avoid lost packets and incorrect ordering

Page 70: Networking with Java Carl Gunter ( gunter@cis ) Arvind Easwaran ( arvinde@saul ) Michael May ( mjmay@saul )

Socket Communication OverviewUDP (User Datagram Protocol) UDP is a connectionless transport layer protocol that

also sits on top of IP Provides no data integrity mechanisms except for

checksum Simply packages it’s data into, what is known as a

Datagram, along with the destination address and port number

If the destination host is alive and listening it will receive the Datagram

No guaranteed delivery, there is a possibility that datagrams will be lost corrupted or delivered in the wrong order

Protocol has few built-in facilities thereby resulting in very low management overhead

Lack of "permanent" connection also means UDP can adapt better to network failures

Examples - DNS lookups, PING

Page 71: Networking with Java Carl Gunter ( gunter@cis ) Arvind Easwaran ( arvinde@saul ) Michael May ( mjmay@saul )

Network byte ordering Standard way in which bytes are

ordered for network communication Network byte order says that the high-

byte (the byte on the right) should be written first and low-byte (the byte on the left) last

For example, the following byte representation of an integer, 10 12 45 32 should be written 32 45 12 10 when sending it across the network

Page 72: Networking with Java Carl Gunter ( gunter@cis ) Arvind Easwaran ( arvinde@saul ) Michael May ( mjmay@saul )

Socket communication: Java Classes

Classes listed below are from java.net and java.io packages

Obtaining Internet address information Class InetAddress

This class provides methods to access host names and IP addresses

The following methods are provided to create InetAddress objects

Static InetAddress getLocalHost() throws UnknownHostException

Static InetAddress getByName(String host) throws UnknownHostException

The host name can be either a pneumonic identifier such as "www.Java.com" or an IP address such as 121.1.28.54

Page 73: Networking with Java Carl Gunter ( gunter@cis ) Arvind Easwaran ( arvinde@saul ) Michael May ( mjmay@saul )

Socket Class

Class Socket These constructors allow the Socket connection to be

established Socket(String host, int port) throws IOException

This creates a Socket and connects to the specified host and port Host can be a host name or IP address and port must be in a

range of 1-65535 Socket(InetAddress address, int port) throws

IOException This creates a Socket and connects to the specified port The port must be in a range of 1-65535

InetAddress getInetAddress() This method returns the IP address of a remote host

int getPort() This method returns the port number of the remote host

int getLocalPort() The local port number is returned by this method

Page 74: Networking with Java Carl Gunter ( gunter@cis ) Arvind Easwaran ( arvinde@saul ) Michael May ( mjmay@saul )

I/O Streams InputStream getInputStream()throws

IOException Returns an InputStream that allows the Socket to

receive data across the TCP connection An InputStream can be buffered or standard

OutputStream getOutputStream()throws IOException Returns an OutputStream that allows the Socket

to send data across the TCP connection An OutputStream should be buffered to avoid lost

bytes, especially when the Socket is closed void close() throws IOException

Closes the Socket, releasing any network resources

Page 75: Networking with Java Carl Gunter ( gunter@cis ) Arvind Easwaran ( arvinde@saul ) Michael May ( mjmay@saul )

Exceptions

IOException Generic I/O error that can be thrown by

many of the methods SecurityException

Thrown if the Java security manager has restricted the desired action

Applets may not open sockets to any host other than the originating host, i.e. the web server

Any attempt to open a socket to a destination other than the host address will cause this exception to be thrown

Page 76: Networking with Java Carl Gunter ( gunter@cis ) Arvind Easwaran ( arvinde@saul ) Michael May ( mjmay@saul )

TCP Client Connections - Sample Code

// Input and output streams for TCP socketprotected DataInputStream in;protected DataOutputStream out;protected Socket connect (int port) throws IOException{

// Connect methodoutput.appendText ("\nHi\n");Socket socket = new Socket (server, port);OutputStream rawOut =

socket.getOutputStream();InputStream rawIn = socket.getInputStream ();BufferedOutputStream buffOut = newBufferedOutputStream (rawOut);out = new DataOutputStream (buffOut);in = new DataInputStream (rawIn);return socket; }

Page 77: Networking with Java Carl Gunter ( gunter@cis ) Arvind Easwaran ( arvinde@saul ) Michael May ( mjmay@saul )

ServerSocket Class The ServerSocket class creates a Socket for each client

connection ServerSocket(int port, int count) throws IOException

Constructs a ServerSocket that listens on the specified port of the local machine

Argument 1 is mandatory, but argument 2, the outstanding connection requests parameter, may be omitted

Default of 50 is used Socket accept() throws IOException

This method blocks until a client makes a connection to the port on which the ServerSocket is listening

void close() throws IOException This method closes the ServerSocket It does not close any of the currently accepted

connections int getLocalPort()

Returns the integer value of the port on which ServerSocket is listening

Page 78: Networking with Java Carl Gunter ( gunter@cis ) Arvind Easwaran ( arvinde@saul ) Michael May ( mjmay@saul )

TCP Server Connections - Code Example

static Socket accept (int port) throws IOException {// Setup ServerSocket

ServerSocket server = new ServerSocket (port);Socket ClientSocket = server.accept ();// Extract the address of the connected userSystem.out.println ("Accepted from " + ClientSocket.getInetAddress ());server.close ();// return the client sock so that communication can beginreturn ClientSocket;} }

Page 79: Networking with Java Carl Gunter ( gunter@cis ) Arvind Easwaran ( arvinde@saul ) Michael May ( mjmay@saul )

Datagram Communication

When using Datagram communication there are several differences to stream based TCP

Firstly a datagram packet is required, as we do not have a "permanent" stream we cannot simply read and write data to and from a communication channel

Instead we must construct datagrams, that contains the destination address, the port number, the data and the length of the data

Therefore we must deal with creating and dissecting packets

Page 80: Networking with Java Carl Gunter ( gunter@cis ) Arvind Easwaran ( arvinde@saul ) Michael May ( mjmay@saul )

DatagramPacket Class Class DatagramPacket

Used to create the datagram packets for transmission and receipt

DatagramPacket(byte inbuf[], int buflength) Constructs a datagram packet for receiving datagrams Inbuff is a byte array that holds the data received and

buflength is the maximum number of bytes to read DatagramPacket(byte inbuf[], int buflength,

InetAddress iaddr, int port) Constructs a datagram packet for transmission iaddr is the address of the destination and port is the port

number on the remote host int getPort()

Returns the port number of the packet byte() getData()

Returns a byte array corresponding to the data in the DatagramPacket

Page 81: Networking with Java Carl Gunter ( gunter@cis ) Arvind Easwaran ( arvinde@saul ) Michael May ( mjmay@saul )

Exampleprotected DatagramPacket buildPacket (String

message, String host, int port) throws IOException {

// Create a byte array from a stringByteArrayOutputStream byteOut = new ByteArrayOutputStream ();DataOutputStream dataOut = new DataOutputStream (byteOut);dataOut.writeBytes(message);byte[] data = byteOut.toByteArray ();

//Return the new object with the byte array payloadreturn new DatagramPacket (data, data.length, InetAddress.getByName(host), port);

}

Page 82: Networking with Java Carl Gunter ( gunter@cis ) Arvind Easwaran ( arvinde@saul ) Michael May ( mjmay@saul )

Class DatagramSocket Used to create sockets for DatagramPackets DatagramSocket(int port) throws

SocketException Creates a DatagramSocket using the specified port

number void send(DatagramPacket p) throws

IOException Sends the packet out onto the network

syncronized void receive(DatagramPacket p) throws IOException

Receives a packet into the specified DatagramPacket

Blocks until a packet has been received successfully.

syncronized void close() Closes the DatagramSocket

Page 83: Networking with Java Carl Gunter ( gunter@cis ) Arvind Easwaran ( arvinde@saul ) Michael May ( mjmay@saul )

Exampleprotected void receivePacket () throws IOException {

byte buffer[] = new byte[65535];DatagramPacket packet = new DatagramPacket

(buffer,buffer.length);socket.receive (packet); // Convert the byte array read from network into a

string ByteArrayInputStream byteIn = newByteArrayInputStream (packet.getData (), 0,packet.getLength ()); DataInputStream dataIn = new DataInputStream(byteIn); // Read in data from a standard format String input = ""; while((input = dataIn.readLine ()) != null) output.appendText("SERVER REPLIED : " + input +); }

Page 84: Networking with Java Carl Gunter ( gunter@cis ) Arvind Easwaran ( arvinde@saul ) Michael May ( mjmay@saul )

Java Cryptography

Page 85: Networking with Java Carl Gunter ( gunter@cis ) Arvind Easwaran ( arvinde@saul ) Michael May ( mjmay@saul )

Goals

Learn about JAVA Crypto Architecture

How to use JAVA Crypto API’s Understand the SunJCE

Implementation Be able to use java crypto functions

(meaningfully) in your code

Page 86: Networking with Java Carl Gunter ( gunter@cis ) Arvind Easwaran ( arvinde@saul ) Michael May ( mjmay@saul )

Introduction JDK Security API

Core API for Java Built around the java.security package

First release of JDK Security introduced "Java Cryptography Architecture" (JCA)

Framework for accessing and developing cryptographic functionality

JCA encompasses Parts of JDK 1.2 Security API related to cryptography Architecture that allows for multiple and interoperable

cryptography implementations The Java Cryptography Extension (JCE) extends JCA

Includes APIs for encryption, key exchange, and Message Authentication Code (MAC)

Page 87: Networking with Java Carl Gunter ( gunter@cis ) Arvind Easwaran ( arvinde@saul ) Michael May ( mjmay@saul )

Java Cryptography Extension (JCE)

Adds encryption, key exchange, key generation, message authentication code (MAC) Multiple “providers” supported Keys & certificates in “keystore”

database Separate due to export control

Page 88: Networking with Java Carl Gunter ( gunter@cis ) Arvind Easwaran ( arvinde@saul ) Michael May ( mjmay@saul )

JCE Architecture

JCE:Cipher

KeyAgreementKeyGenerator

SecretKeyFactoryMAC

CSP 1 CSP 2

SPI

APIApp 1 App 2

Page 89: Networking with Java Carl Gunter ( gunter@cis ) Arvind Easwaran ( arvinde@saul ) Michael May ( mjmay@saul )

Design Principles Implementation independence and

interoperability "provider“ based architecture Set of packages implementing cryptographic services

digital signature algorithms Programs request a particular type of object Various implementations working together, use each

other's keys, or verify each other's signatures

Algorithm independence and extensibility Cryptographic classes providing the functionality Classes are called engine classes, example Signature Addition of new algorithms straight forward

Page 90: Networking with Java Carl Gunter ( gunter@cis ) Arvind Easwaran ( arvinde@saul ) Michael May ( mjmay@saul )

Building Blocks Key Certificate Keystore Message Digest Digital Signature SecureRandom Cipher MAC

Page 91: Networking with Java Carl Gunter ( gunter@cis ) Arvind Easwaran ( arvinde@saul ) Michael May ( mjmay@saul )

Engine Classes and SPI Interface to specific type of cryptographic service Defines API methods to access cryptographic service Actual implementation specific to algorithms For example : Signature engine class

Provides access to the functionality of a digital signature algorithm

Actual implementation supplied by specific algorithm subclass

"Service Provider Interface" (SPI) Each engine class has a corresponding abstract SPI

class Defines the Service Provider Interface to be used by

implementors

SPI class is abstract - To supply implementation, provider must subclass

Page 92: Networking with Java Carl Gunter ( gunter@cis ) Arvind Easwaran ( arvinde@saul ) Michael May ( mjmay@saul )

JCA Implementation

SPI (Service Provider Interface) say FooSpi

Engine Foo Algorithm MyAlgorithm

Foo f = Foo.getInstance(MyAlgorithm);

Page 93: Networking with Java Carl Gunter ( gunter@cis ) Arvind Easwaran ( arvinde@saul ) Michael May ( mjmay@saul )

General Usage

No need to call constructor directly Define the algorithm reqd.

getInstance() Initialize the keysize

init() or initialize() Use the Object generateKey() or doFinal()

Page 94: Networking with Java Carl Gunter ( gunter@cis ) Arvind Easwaran ( arvinde@saul ) Michael May ( mjmay@saul )

java.security classes Key KeyPair KeyPairGenerator KeyFactory Certificate CertificateFactory Keystore MessageDigest Signature SignedObject SecureRandom

Page 95: Networking with Java Carl Gunter ( gunter@cis ) Arvind Easwaran ( arvinde@saul ) Michael May ( mjmay@saul )

Key Types

SecretKey PublicKey PrivateKey

Methods getAlgorthm() getEncoded()

KeyPair= {PrivateKey, PublicKey}

Page 96: Networking with Java Carl Gunter ( gunter@cis ) Arvind Easwaran ( arvinde@saul ) Michael May ( mjmay@saul )

KeyGenerator

Generates instances of key Requires Algorithm

getInstance(algo) Keylength, (random)

Initialize(param, random) Generates required key/keypair

Page 97: Networking with Java Carl Gunter ( gunter@cis ) Arvind Easwaran ( arvinde@saul ) Michael May ( mjmay@saul )

KeyFactory/SecretKeyFactory

Converts a KeySpec into Keys KeySpec Depends on the algorithm Usually a byte[] (DES)

Could also be a set of numbers (DSA)

Required when the key is encoded and transferred across the network

Page 98: Networking with Java Carl Gunter ( gunter@cis ) Arvind Easwaran ( arvinde@saul ) Michael May ( mjmay@saul )

Certificate Problem

Java.security.Certificate is an interface Java.security.cert.Certificate is a class

Which one to use when you ask for a Certificate? Import only the correct type

Avoid “import java.security.*” Use X509Certificate

Page 99: Networking with Java Carl Gunter ( gunter@cis ) Arvind Easwaran ( arvinde@saul ) Michael May ( mjmay@saul )

KeyStore

Access to a physical keystore Can import/export certificates

Can import keys from certificates Certificate.getPublicKey()

Certificate.getPrivateKey() Check for certificate validity Check for authenticity

Page 100: Networking with Java Carl Gunter ( gunter@cis ) Arvind Easwaran ( arvinde@saul ) Michael May ( mjmay@saul )

keytool

Reads/writes to a keystore Unique alias for each certificate Password Encrypted

Functionality Import Sign Request

Export NOTE: Default is DSA !

Page 101: Networking with Java Carl Gunter ( gunter@cis ) Arvind Easwaran ( arvinde@saul ) Michael May ( mjmay@saul )

Signature

DSA, RSA Obtain a Signature Object getInstance(algo) getInstance(algorithm,provider)

Page 102: Networking with Java Carl Gunter ( gunter@cis ) Arvind Easwaran ( arvinde@saul ) Michael May ( mjmay@saul )

Signature (signing) Initialize for signing initSign(PrivateKey)

Give the data to be signed update(byte [] input) and variations

doFinal(byte [] input) and variations Sign

byte[] Signature.sign() NOTE: Signature does not contain the actual signature

Page 103: Networking with Java Carl Gunter ( gunter@cis ) Arvind Easwaran ( arvinde@saul ) Michael May ( mjmay@saul )

Signature (verifying)

Initialize for verifying initVerify(PublicKey)

Give the data to be verifieded update(byte [] input) and variations

doFinal(byte [] input) and variations Verify boolean Signature.verify()

Page 104: Networking with Java Carl Gunter ( gunter@cis ) Arvind Easwaran ( arvinde@saul ) Michael May ( mjmay@saul )

SignedObject Signs and encapsulates a signed object

Sign SignedObject(Serializable, Signature)

Recover Object getContent()

byte[] getSignature() Verify

Verify(PublicKey, Signature) ! Need to initialize the instance of the signature

Page 105: Networking with Java Carl Gunter ( gunter@cis ) Arvind Easwaran ( arvinde@saul ) Michael May ( mjmay@saul )

javax.crypto classes

Cipher Mac KeyGenerator SecretKeyFactory SealedObject

Page 106: Networking with Java Carl Gunter ( gunter@cis ) Arvind Easwaran ( arvinde@saul ) Michael May ( mjmay@saul )

Cipher DES, DESede, RSA, Blowfish, IDEA …

Obtain a Cipher Object getInstance(algorithm/mode/padding) or getInstance(algorithm)

or getInstance(algorithm, provider) eg “DES/ECB/NoPadding” or “RSA” Initialize init(mode, key) mode= ENCRYPT_MODE / DECRYPT_MODE

Page 107: Networking with Java Carl Gunter ( gunter@cis ) Arvind Easwaran ( arvinde@saul ) Michael May ( mjmay@saul )

Cipher cont. Encrypt/Decrypt

byte[] update(byte [] input) and variations

byte[] doFinal(byte [] input) and variations Exceptions NoSuchAlgorithmException NoSuchPadding Exception InvalidKeyException

Page 108: Networking with Java Carl Gunter ( gunter@cis ) Arvind Easwaran ( arvinde@saul ) Michael May ( mjmay@saul )

SealedObject Encrypts and encapsulates an

encrypted object Encrypt

SealedObject(Serializable, Cipher) Recover getObject(Cipher)

or getObject(key) Cipher mode should be different!!

Page 109: Networking with Java Carl Gunter ( gunter@cis ) Arvind Easwaran ( arvinde@saul ) Michael May ( mjmay@saul )

Wrapper Class : Crypto.java

Adding a provider public Crypto() {

java.security.Security.addProvider(new cryptix.provider.Cryptix());}

Page 110: Networking with Java Carl Gunter ( gunter@cis ) Arvind Easwaran ( arvinde@saul ) Michael May ( mjmay@saul )

Enrcyption using RSApublic synchronized byte[]

encryptRSA(Serializable obj, PublicKey kPub) throws KeyException, IOException {try { Cipher RSACipher = Cipher.getInstance("RSA"); return encrypt(RSACipher, obj, kPub);} catch (NoSuchAlgorithmException e) { System.exit(1);}return null; }

Page 111: Networking with Java Carl Gunter ( gunter@cis ) Arvind Easwaran ( arvinde@saul ) Michael May ( mjmay@saul )

Decryption using RSApublic synchronized Object decryptRSA(byte[]

msgE, PrivateKey kPriv)throws KeyException, IOException

{try { Cipher RSACipher = Cipher.getInstance("RSA"); return decrypt(RSACipher, msgE, kPriv);} catch (NoSuchAlgorithmException e) { System.exit(1);}return null; }

Page 112: Networking with Java Carl Gunter ( gunter@cis ) Arvind Easwaran ( arvinde@saul ) Michael May ( mjmay@saul )

Creating a signaturepublic synchronized byte[] sign(byte[] msg, PrivateKey kPriv) throws SignatureException, KeyException, IOException

{// Initialize the signature object for signingdebug("Initializing signature.");try { Signature RSASig = Signature.getInstance("SHA-1/RSA/PKCS#1"); debug("Using algorithm: " + RSASig.getAlgorithm()); RSASig.initSign(kPriv); RSASig.update(msg); return RSASig.sign();} catch (NoSuchAlgorithmException e) { System.exit(1);}return null; }

Page 113: Networking with Java Carl Gunter ( gunter@cis ) Arvind Easwaran ( arvinde@saul ) Michael May ( mjmay@saul )

Verifying a signaturepublic synchronized boolean verify(byte[] msg, byte[] sig,

PublicKey kPub) throws SignatureException, KeyException

{// Initialize the signature object for verifyingdebug("Initializing signature.");try { Signature RSASig = Signature.getInstance("SHA-1/RSA/PKCS#1"); RSASig.initVerify(kPub); RSASig.update(msg); return RSASig.verify(sig);} catch (NoSuchAlgorithmException e) { System.exit(1);}return false; }

Page 114: Networking with Java Carl Gunter ( gunter@cis ) Arvind Easwaran ( arvinde@saul ) Michael May ( mjmay@saul )

References

Sun’s Java website: http://java.sun.com

Page 115: Networking with Java Carl Gunter ( gunter@cis ) Arvind Easwaran ( arvinde@saul ) Michael May ( mjmay@saul )

Thanks for staying awake