74
1 Week 2 “Just Java” by Linden chapters 4,5,13 Java I/O and Client/Server me of the material on I/O and client/server is from kel’s “Thinking in Java”

1 Week 2 “Just Java” by Linden chapters 4,5,13 Java I/O and Client/Server Some of the material on I/O and client/server is from Bruce Eckel’s “Thinking

  • View
    222

  • Download
    0

Embed Size (px)

Citation preview

Page 1: 1 Week 2 “Just Java” by Linden chapters 4,5,13 Java I/O and Client/Server Some of the material on I/O and client/server is from Bruce Eckel’s “Thinking

1

Week 2

• “Just Java” by Linden chapters 4,5,13

• Java I/O and Client/Server

Some of the material on I/O and client/server is from BruceEckel’s “Thinking in Java”

Page 2: 1 Week 2 “Just Java” by Linden chapters 4,5,13 Java I/O and Client/Server Some of the material on I/O and client/server is from Bruce Eckel’s “Thinking

2

Notes From “Just Java”

Chapter 4

Page 3: 1 Week 2 “Just Java” by Linden chapters 4,5,13 Java I/O and Client/Server Some of the material on I/O and client/server is from Bruce Eckel’s “Thinking

3

Comments

// a single line comment

/* a multi-line comment*/

/** a javadoc comment*/

javadoc MyDocumentedProgram.java produces .html files

Page 4: 1 Week 2 “Just Java” by Linden chapters 4,5,13 Java I/O and Client/Server Some of the material on I/O and client/server is from Bruce Eckel’s “Thinking

4

Casts// we can cast a float or double to an int with truncationfloat f = 3.142;int i = (int) f;

// we can cast an int to a short with truncationshort s = (short) 123456; System.out.println(s);

C:\McCarthy\www\JustJava\Examples>java TestCast-7616

Page 5: 1 Week 2 “Just Java” by Linden chapters 4,5,13 Java I/O and Client/Server Some of the material on I/O and client/server is from Bruce Eckel’s “Thinking

5

Char type

16-bit Unicode

A single char constant looks like ‘A’ in single quotes.

May be used as an unsigned short

char s = (char) -1; int x = s; System.out.println(x);

C:\McCarthy\www\JustJava\Examples>java TestUnsigned 65535

Page 6: 1 Week 2 “Just Java” by Linden chapters 4,5,13 Java I/O and Client/Server Some of the material on I/O and client/server is from Bruce Eckel’s “Thinking

6

String Class – use .equals()public class TestString { public static void main(String a[]) {

String x = "A simple string"; String y = "A simple"; y = y + " string"; if(x == y) System.out.println("They are equal with == "); else if(x.equals(y)) System.out.println("They are equal with .equals()"); else System.out.println("Not equal with == or with .equals()"); }} C:\McCarthy\www\JustJava\Examples>java TestString

They are equal with .equals()

Page 7: 1 Week 2 “Just Java” by Linden chapters 4,5,13 Java I/O and Client/Server Some of the material on I/O and client/server is from Bruce Eckel’s “Thinking

7

Notes From “Just Java”

Chapter 5

Page 8: 1 Week 2 “Just Java” by Linden chapters 4,5,13 Java I/O and Client/Server Some of the material on I/O and client/server is from Bruce Eckel’s “Thinking

8

Forward References

// works fine

class Fruit {

void foo() { grams = 22; } int grams;}

Page 9: 1 Week 2 “Just Java” by Linden chapters 4,5,13 Java I/O and Client/Server Some of the material on I/O and client/server is from Bruce Eckel’s “Thinking

9

Arrays

Two steps:

int a[]; a = new int[10];

Fruit b[]; b = new Fruit[345]; // no Fruit objects yet // don’t call b[4].foo()

See book for initialization syntax.

Page 10: 1 Week 2 “Just Java” by Linden chapters 4,5,13 Java I/O and Client/Server Some of the material on I/O and client/server is from Bruce Eckel’s “Thinking

10

Arrays can be cloned

public class TestSheep {

public static void main(String a[]) {

int sheep[] = new int[10]; sheep[4] = 99; int baaa[] = (int[]) sheep.clone(); System.out.println(baaa[4]); }}

C:\McCarthy\www\JustJava\Examples>java TestSheep99

Page 11: 1 Week 2 “Just Java” by Linden chapters 4,5,13 Java I/O and Client/Server Some of the material on I/O and client/server is from Bruce Eckel’s “Thinking

11

Most operators are the same as c

Order of operations is clearly defined in Java.

Precedence says which operators bind first.

Associativity is the tie breaker when operators are of equalprecedence.

Order of operations is strictly left to right in Java.

Page 12: 1 Week 2 “Just Java” by Linden chapters 4,5,13 Java I/O and Client/Server Some of the material on I/O and client/server is from Bruce Eckel’s “Thinking

12

Examplepublic class TestSheep {

public static void main(String a[]) {

int i = 8; int m[] = new int[10];

m[i] = (i = 2) * i++; System.out.println("m[8] == " + m[8] + " and i == " + i);

}} C:\McCarthy\www\JustJava\Examples>java TestSheep

m[8] == 4 and i == 3

Page 13: 1 Week 2 “Just Java” by Linden chapters 4,5,13 Java I/O and Client/Server Some of the material on I/O and client/server is from Bruce Eckel’s “Thinking

13

What Happens on Overflow?

When an integer valued expression is too big for itstype the lowend bytes are stored and we have no report of overflow.

byte b = (int) 10000;

An exception is thrown for division by 0.

Page 14: 1 Week 2 “Just Java” by Linden chapters 4,5,13 Java I/O and Client/Server Some of the material on I/O and client/server is from Bruce Eckel’s “Thinking

14

Examplepublic class TestOverflow {

public static void main(String a[]) {

byte i = 8; byte m = 0; i = (byte) (i % m);

}}

C:\McCarthy\www\JustJava\Examples>java TestOverflowException in thread "main" java.lang.ArithmeticException: / by zero at TestOverflow.main(TestOverflow.java:7)

Page 15: 1 Week 2 “Just Java” by Linden chapters 4,5,13 Java I/O and Client/Server Some of the material on I/O and client/server is from Bruce Eckel’s “Thinking

15

Adding a try/catch blockpublic class TestOverflow { public static void main(String a[]) { try { byte i = 8; byte m = 0; i = (byte) (i % m); } catch(ArithmeticException e) { System.out.println("That did not go well"); } System.out.println("Terminating"); }}

C:\McCarthy\www\JustJava\Examples>java TestOverflowThat did not go wellTerminating

Page 16: 1 Week 2 “Just Java” by Linden chapters 4,5,13 Java I/O and Client/Server Some of the material on I/O and client/server is from Bruce Eckel’s “Thinking

16

Notes From Bruce Eckel’s Thinking in Java

“Just Java” Chapter 13

Simple I/O

Page 17: 1 Week 2 “Just Java” by Linden chapters 4,5,13 Java I/O and Client/Server Some of the material on I/O and client/server is from Bruce Eckel’s “Thinking

17

JAVA I/O and Client/Server

Page 18: 1 Week 2 “Just Java” by Linden chapters 4,5,13 Java I/O and Client/Server Some of the material on I/O and client/server is from Bruce Eckel’s “Thinking

18

The Java IO System

• Different kinds of IO

– Files, the console, blocks of memory,

network connections

• Different kinds of operations

– Sequential, random- access, binary,

character, by lines, by words, etc.

Source: Eckel

Page 19: 1 Week 2 “Just Java” by Linden chapters 4,5,13 Java I/O and Client/Server Some of the material on I/O and client/server is from Bruce Eckel’s “Thinking

19

• Seems like a lot of classes

• Also seems at first like an odd design

– Not typically how you think of using classes

– Can require a lot of typing

• There is a plan

– A learning experience in class design

– The “Decorator” Design Pattern

The Java IO Library Design

Source: Eckel

Page 20: 1 Week 2 “Just Java” by Linden chapters 4,5,13 Java I/O and Client/Server Some of the material on I/O and client/server is from Bruce Eckel’s “Thinking

20

• InputStream (Abstract class)

This abstract class is the superclass of all classes

representing an input stream of bytes.

• OutputStream (Abstract class)

This abstract class is the superclass of all classes

representing an output stream of bytes.

InputStream and OutputStream

Source: Eckel

Page 21: 1 Week 2 “Just Java” by Linden chapters 4,5,13 Java I/O and Client/Server Some of the material on I/O and client/server is from Bruce Eckel’s “Thinking

21

ByteArrayInputStream read memory block

StringBufferInputStream read from String (not buffer)

FileInputStream read from file

PipedInputStream read from another thread

SequenceInputStream reads from several streams

FilterInputStream Decorators subclass this class.

A FilterInputStream contains some other input stream, which it uses as its basic source of data, possibly transforming the data along the way or providing additional functionality.

Types of InputStream

Page 22: 1 Week 2 “Just Java” by Linden chapters 4,5,13 Java I/O and Client/Server Some of the material on I/O and client/server is from Bruce Eckel’s “Thinking

22

• DataInputStream (binary data)

• Full interface for reading primitive and built- in types

• Construct with an InputStream

• When reading a float, four bytes are read

• BufferedInputStream

• Adds buffering to the stream (usually do this)

• Construct with an InputStream

Two important FilterInputStream classes -- Decorators

Page 23: 1 Week 2 “Just Java” by Linden chapters 4,5,13 Java I/O and Client/Server Some of the material on I/O and client/server is from Bruce Eckel’s “Thinking

23

FileInputStream - Reading Data From a FileBufferedInputStream – Buffers inputDataInputStream – Reading binary data readLine() -- deprecated

File Name

File Name

DataInputStream

BufferedInputStream

FileInputStream

String Source of data

Decorators

Page 24: 1 Week 2 “Just Java” by Linden chapters 4,5,13 Java I/O and Client/Server Some of the material on I/O and client/server is from Bruce Eckel’s “Thinking

24

// copy a binary or text file

import java.io.*;

public class CopyBytes {

public static void main( String args[]) throws IOException {

DataInputStream in =

new DataInputStream(

new BufferedInputStream(

new FileInputStream(args[0])));

DataOutputStream out =

new DataOutputStream(

new BufferedOutputStream(

new FileOutputStream(args[1])));

Page 25: 1 Week 2 “Just Java” by Linden chapters 4,5,13 Java I/O and Client/Server Some of the material on I/O and client/server is from Bruce Eckel’s “Thinking

25

byte byteIn;

try {

while(true) {

byteIn = in.readByte();

out.writeByte(byteIn);

}

}

catch(EOFException e) {

in.close();

out.close();

}

}

}

Page 26: 1 Week 2 “Just Java” by Linden chapters 4,5,13 Java I/O and Client/Server Some of the material on I/O and client/server is from Bruce Eckel’s “Thinking

26

ByteArrayOutputStream Block of memory

FileOutputStream File

PipedOutputStream “Pipe” (to another thread)

FilterOutputStream Decorators subclass this

class

Types of OutputStream Writes to:

Page 27: 1 Week 2 “Just Java” by Linden chapters 4,5,13 Java I/O and Client/Server Some of the material on I/O and client/server is from Bruce Eckel’s “Thinking

27

• DataOutputStream

– Full interface for writing primitive and built-in types; complements

DataInputStream for portable reading & writing of data

DataOutputStream is normally for storage.

• PrintStream

– Allows primitive formatting for data display. Not as nice a

c’s printf(). Converts arguments to ASCII or EBCDIC. Use

PrintWriter when writing Unicode characters rather than bytes.

• BufferedOutputStream – Adds a buffer (usually do this).

Three important FilterOutputStream classes -- Decorators

Page 28: 1 Week 2 “Just Java” by Linden chapters 4,5,13 Java I/O and Client/Server Some of the material on I/O and client/server is from Bruce Eckel’s “Thinking

28

Writing ASCII Data To A FilePrintStream writes in the platform’s defaultencoding.

File Name

File Name

PrintStream

BufferedOutputStream

FileOutputStream

String Sink

Decorators

Page 29: 1 Week 2 “Just Java” by Linden chapters 4,5,13 Java I/O and Client/Server Some of the material on I/O and client/server is from Bruce Eckel’s “Thinking

29

// Writing ASCII data to a file

import java.io.*;

public class OutPutDemo {

public static void main(String args[]) throws FileNotFoundException{

PrintStream out = new PrintStream(

new BufferedOutputStream(

new FileOutputStream("IODemo.out")));

out.println("Hello world...on a file");

out.close();

}

}

Page 30: 1 Week 2 “Just Java” by Linden chapters 4,5,13 Java I/O and Client/Server Some of the material on I/O and client/server is from Bruce Eckel’s “Thinking

30

DataOutPutStream is for binary output.DataInputStream is for reading binary.

DataOutputStream

BufferedOutputStream

FileOutputStream

String Sink

Decorators

Page 31: 1 Week 2 “Just Java” by Linden chapters 4,5,13 Java I/O and Client/Server Some of the material on I/O and client/server is from Bruce Eckel’s “Thinking

31

// Writing data to a file In Binary not ASCII import java.io.*;public class OutPutDemo {public static void main(String args[]) throws FileNotFoundException, IOException { DataOutputStream out = new DataOutputStream ( new BufferedOutputStream( new FileOutputStream("Binary.out"))); out.writeDouble(3.34); // can’t view this!! out.writeDouble(2.33); out.close(); }}

Page 32: 1 Week 2 “Just Java” by Linden chapters 4,5,13 Java I/O and Client/Server Some of the material on I/O and client/server is from Bruce Eckel’s “Thinking

32

Readers and Writers

• New in Java 1.1• Provide Unicode-compliant, character-based I/O• Similar in structure to the InputStream and OutputStream “byte” hierarchy

Page 33: 1 Week 2 “Just Java” by Linden chapters 4,5,13 Java I/O and Client/Server Some of the material on I/O and client/server is from Bruce Eckel’s “Thinking

33

PrintWriter has replaced PrintStream for text output.

PrintWriter

BufferedWriter

FileWriter

String Sink

Decorators

Page 34: 1 Week 2 “Just Java” by Linden chapters 4,5,13 Java I/O and Client/Server Some of the material on I/O and client/server is from Bruce Eckel’s “Thinking

34

// Writing data to a file -- improves on the old PrintStream

import java.io.*;

public class OutPutDemo {

public static void main(String args[]) throws

FileNotFoundException, IOException {

PrintWriter out = new PrintWriter(

new BufferedWriter(

new FileWriter("IODemo.out")));

out.println("Hello world...on a file");

out.close();

}

}

Page 35: 1 Week 2 “Just Java” by Linden chapters 4,5,13 Java I/O and Client/Server Some of the material on I/O and client/server is from Bruce Eckel’s “Thinking

35

Inputstream

InputStreamReader

BufferedReader

A System.in object is of type InputStream

Converting from an 8-bit InputStream to 16-bit Unicode

Converts from an InputStreamto a Reader

Page 36: 1 Week 2 “Just Java” by Linden chapters 4,5,13 Java I/O and Client/Server Some of the material on I/O and client/server is from Bruce Eckel’s “Thinking

36

import java.io.*;

public class InputDemo {

public static void main(String args[]) throws IOException

{

BufferedReader in =

new BufferedReader(

new InputStreamReader(System.in));

System.out.println("What is your name?");

String name = in.readLine();

System.out.println("Hello "+ name);

}

}

Page 37: 1 Week 2 “Just Java” by Linden chapters 4,5,13 Java I/O and Client/Server Some of the material on I/O and client/server is from Bruce Eckel’s “Thinking

37

BufferedReader

InputStreamReader

FileInputStream

String

InputStream

Reader

Page 38: 1 Week 2 “Just Java” by Linden chapters 4,5,13 Java I/O and Client/Server Some of the material on I/O and client/server is from Bruce Eckel’s “Thinking

38

import java.io.*; // Read and write an ASCII filepublic class InputDemo {public static void main(String args[]) throws IOException { BufferedReader in = new BufferedReader( new InputStreamReader( new FileInputStream("IODemo.in"))); String line;

while((line = in.readLine()) != null) System.out.println(line); }}

Page 39: 1 Week 2 “Just Java” by Linden chapters 4,5,13 Java I/O and Client/Server Some of the material on I/O and client/server is from Bruce Eckel’s “Thinking

39

Some Examples

// Demonstrate character I/O in Java// Count the number of a's and b's

import java.io.*;

public class CharIO {

public static void main(String arg[]) throws IOException {

InputStreamReader is = new InputStreamReader(System.in);

System.out.println("Enter a line of text and I'll count the a's and b's");

Page 40: 1 Week 2 “Just Java” by Linden chapters 4,5,13 Java I/O and Client/Server Some of the material on I/O and client/server is from Bruce Eckel’s “Thinking

40

int aCount = 0;

int bCount = 0;

int i; // i should be an int so that we can detect a -1 from

// the read method. -1 is returned when read() sees

// <ctrl><z> in DOS

i = is.read();

while(i != '\n') {

char c = (char) i;

if(c == 'a') aCount++;

if(c == 'b') bCount++;

i = is.read();

}

System.out.println("a total = " + aCount + " b total = " + bCount);

}}

Page 41: 1 Week 2 “Just Java” by Linden chapters 4,5,13 Java I/O and Client/Server Some of the material on I/O and client/server is from Bruce Eckel’s “Thinking

41

Some Examples Count lines

// Demonstrate character I/O in Java// Echo the input and count lines

import java.io.*;

public class CharIO2 {

public static void main(String arg[]) throws IOException {

InputStreamReader is = new InputStreamReader(System.in);

Page 42: 1 Week 2 “Just Java” by Linden chapters 4,5,13 Java I/O and Client/Server Some of the material on I/O and client/server is from Bruce Eckel’s “Thinking

42

System.out.println("I'll echo and count lines");

int lineCount = 0;

int i;

i = is.read(); // -1 = EOF = <ctrl><z> in DOS

while(i != -1) {

char c = (char) i;

if(c == '\n') lineCount++;

System.out.print(c);

i = is.read();

}

System.out.println("--------------------------");

System.out.println("Line count == " + lineCount);

}

}

Page 43: 1 Week 2 “Just Java” by Linden chapters 4,5,13 Java I/O and Client/Server Some of the material on I/O and client/server is from Bruce Eckel’s “Thinking

43

// Read a line of integers

// and display their sum

import java.io.*;

import java.util.*; // for StringTokenizer

public class LineOfInts {

public static void main(String arg[]) throws IOException

{

Some Examples Using StringTokenizer

Page 44: 1 Week 2 “Just Java” by Linden chapters 4,5,13 Java I/O and Client/Server Some of the material on I/O and client/server is from Bruce Eckel’s “Thinking

44

InputStreamReader is = new InputStreamReader(System.in);

BufferedReader br = new BufferedReader(is);

StringTokenizer st;

System.out.println("Enter a line of integers");

String s = br.readLine();

// use comma, space, and tab for delimeters

t = new StringTokenizer(s, ", \t");

Page 45: 1 Week 2 “Just Java” by Linden chapters 4,5,13 Java I/O and Client/Server Some of the material on I/O and client/server is from Bruce Eckel’s “Thinking

45

int sum = 0;

while(st.hasMoreElements()) {

int val = Integer.parseInt(st.nextToken());

sum += val;

}

System.out.println("The sum is " + sum);

}

}

Page 46: 1 Week 2 “Just Java” by Linden chapters 4,5,13 Java I/O and Client/Server Some of the material on I/O and client/server is from Bruce Eckel’s “Thinking

46

Some Examples Formatting a double

// display a number rounded to two decimal places// at least one digit to the left of the decimal point// # means a digit, 0 shows as absentimport java.io.*;import java.text.*; public class FormattedOutput { static final double myDouble = 456.346; public static void main(String arg[]) throws IOException { DecimalFormat df = new DecimalFormat("0.00");

System.out.println(df.format(myDouble)); // displays 456.35

}}

Page 47: 1 Week 2 “Just Java” by Linden chapters 4,5,13 Java I/O and Client/Server Some of the material on I/O and client/server is from Bruce Eckel’s “Thinking

47

// Java I/O// Read a double and display its square rootimport java.io.*;

public class DoubleIO { public static void main(String arg[]) throws IOException { InputStreamReader is = new InputStreamReader(System.in); BufferedReader br = new BufferedReader(is);

Some Examples

Page 48: 1 Week 2 “Just Java” by Linden chapters 4,5,13 Java I/O and Client/Server Some of the material on I/O and client/server is from Bruce Eckel’s “Thinking

48

double x; System.out.println("Enter a double and I'll compute the square root"); String inputString = br.readLine(); x = Double.parseDouble(inputString); // displays NAN if x < 0 System.out.println("The square root of "+x+" is " + Math.sqrt(x)); }}

Page 49: 1 Week 2 “Just Java” by Linden chapters 4,5,13 Java I/O and Client/Server Some of the material on I/O and client/server is from Bruce Eckel’s “Thinking

49

Object Serialization I/O

• Save or restore an object• Works across networks (RMI arguments and

return values)• Compensates for differences in operating

systems• All relevant parts of an Object

magically stored and retrieved; even “web of

objects”

Page 50: 1 Week 2 “Just Java” by Linden chapters 4,5,13 Java I/O and Client/Server Some of the material on I/O and client/server is from Bruce Eckel’s “Thinking

50

Object serialization

• Class must implement Serializable

• Wrap a stream in a ObjectOutputStream (for writing) or ObjectInputStream (for reading)

• Use writeObject( ) and readObject( )

Page 51: 1 Week 2 “Just Java” by Linden chapters 4,5,13 Java I/O and Client/Server Some of the material on I/O and client/server is from Bruce Eckel’s “Thinking

51

An Example Writing BigIntegers

import java.math.*;import java.io.*;

public class TestBigInts { // Streams work with binary bytes

public static void main(String args[]) throws IOException {

BigInteger x = new BigInteger("1234567891011121314"); BigInteger y = new BigInteger("1234567890000000000");

ObjectOutputStream out = new ObjectOutputStream( new FileOutputStream("bigints.dat")); out.writeObject("Big Integer Storage"); out.writeObject(x); out.writeObject(y); }}

Use OutputStream NOT Writer

Page 52: 1 Week 2 “Just Java” by Linden chapters 4,5,13 Java I/O and Client/Server Some of the material on I/O and client/server is from Bruce Eckel’s “Thinking

52

Another Example Reading BigIntegers

import java.math.*;import java.io.*;

public class TestBigInts {

public static void main(String args[]) throws IOException, ClassNotFoundException { BigInteger x, y; ObjectInputStream in = new ObjectInputStream( new FileInputStream("bigints.dat")); String s = (String)in.readObject();

x = (BigInteger)in.readObject(); y = (BigInteger)in.readObject();

System.out.println(s + " " + x + " " + y); }}

Page 53: 1 Week 2 “Just Java” by Linden chapters 4,5,13 Java I/O and Client/Server Some of the material on I/O and client/server is from Bruce Eckel’s “Thinking

53

Some Examples List serialization

import java.util.*;import java.io.*;

public class SaveAList implements Serializable {

public static void main(String args[])throws IOException, ClassNotFoundException {

LinkedList stack = new LinkedList();

stack.addFirst("Little Cat A"); stack.addFirst("Little Cat B"); stack.addFirst("Little Cat C");

Page 54: 1 Week 2 “Just Java” by Linden chapters 4,5,13 Java I/O and Client/Server Some of the material on I/O and client/server is from Bruce Eckel’s “Thinking

54

ObjectOutputStream out = new ObjectOutputStream( new FileOutputStream("CatStack.out")); out.writeObject("The cat and the hat's hat cats"); out.writeObject(stack); out.close();

ObjectInputStream in = new ObjectInputStream( new FileInputStream("CatStack.out")); String s = (String) in.readObject(); LinkedList anotherStack = (LinkedList) in.readObject();

System.out.println(s + anotherStack);

}}

Page 55: 1 Week 2 “Just Java” by Linden chapters 4,5,13 Java I/O and Client/Server Some of the material on I/O and client/server is from Bruce Eckel’s “Thinking

55

C:\McCarthy\46935\io\Serialization>java SaveAListThe cat and the hat's hat cats[Little Cat C, Little Cat B, Little Cat A]

Output

Page 56: 1 Week 2 “Just Java” by Linden chapters 4,5,13 Java I/O and Client/Server Some of the material on I/O and client/server is from Bruce Eckel’s “Thinking

56

• Historically error- prone, difficult, complex

• Threading is very useful and relatively

easy here

• Excellent reference: “Java Network

Programming” by Elliotte Rusty Harold,

O’Reilly Books, 1997.

I/O on the Net

Source: Eckel

Page 57: 1 Week 2 “Just Java” by Linden chapters 4,5,13 Java I/O and Client/Server Some of the material on I/O and client/server is from Bruce Eckel’s “Thinking

57

• Uniquely identify a machine from all the others in the world• IP (Internet Protocol) address that can exist in two forms:

1) DNS (Domain Name Service) form: hempel.heinz.cmu.edu 2) “Dotted quad” form: 128.2.240.92

• Represented internally by 32 bit number (4.3 billion possibilities. Oops!) (going to 128)• static InetAddress.getByName( ) produces a Java object containing address

Identifying a Machine

Source: Eckel

Page 58: 1 Week 2 “Just Java” by Linden chapters 4,5,13 Java I/O and Client/Server Some of the material on I/O and client/server is from Bruce Eckel’s “Thinking

58

• Two machines must connect

• Server waits around for connection

• Client initiates connection

• Once the connection is made, server & client look identical

• Both ends are turned into InputStream and OutputStream objects, which can then be converted to Reader and Writer objects

Servers & Clients

Source: Eckel

Page 59: 1 Week 2 “Just Java” by Linden chapters 4,5,13 Java I/O and Client/Server Some of the material on I/O and client/server is from Bruce Eckel’s “Thinking

59

You might not trust your code

• localhost : the “local loopback” IP address for testing without a network InetAddress addr = InetAddress.getByName(null);

• Equivalently: InetAddress.getByName("localhost");

• Or using the reserved IP number for the loopback:InetAddress.getByName("127.0.0.1");

• open two windows and talk

Testing w/ o a Network

Page 60: 1 Week 2 “Just Java” by Linden chapters 4,5,13 Java I/O and Client/Server Some of the material on I/O and client/server is from Bruce Eckel’s “Thinking

60

• IP address isn’t enough to identify a unique server

• Many servers can exist on one machine

Protocol Port http server 80 ftp server 21 telnet 23 finger 79

• A “server” is a program watching a port.

Port: Unique “Place” in a Machine

Page 61: 1 Week 2 “Just Java” by Linden chapters 4,5,13 Java I/O and Client/Server Some of the material on I/O and client/server is from Bruce Eckel’s “Thinking

61

• When you set up client and server, you must

specify IP address and port, so they can find each

other

• Not a physical location, but a software abstraction

to represent a service

• 1- 1024 are reserved (on Unix, root may access

these ports), higher numbered ports are available

Ports

Page 62: 1 Week 2 “Just Java” by Linden chapters 4,5,13 Java I/O and Client/Server Some of the material on I/O and client/server is from Bruce Eckel’s “Thinking

62

• Software abstraction used to represent the “terminals” of a connection between two machines

• Socket is the actual 2- way connector. Can initiate a connection with a server

• ServerSocket isn’t really a socket but more of a “ServerConnector” that produces a Socket as the return value of accept( ) , which waits (blocks) for a connection.

• In the end, you get a Socket on each machine

Sockets

Page 63: 1 Week 2 “Just Java” by Linden chapters 4,5,13 Java I/O and Client/Server Some of the material on I/O and client/server is from Bruce Eckel’s “Thinking

63

Just Like Files...

• Once you have a Socket , you call getInputStream( ) and getOutputStream( ) to produce the corresponding InputStream and OutputStream objects

• You convert these to readers and writers, wrap them in a BufferedReader or BufferedWriter and PrintWriter

• From then on, it’s like reading and writing any other IO stream!

Page 64: 1 Week 2 “Just Java” by Linden chapters 4,5,13 Java I/O and Client/Server Some of the material on I/O and client/server is from Bruce Eckel’s “Thinking

64

// JabberServer. Java From Bruce Eckel’s text// Very simple server that just// echoes whatever the client sends.// One client at a time. No threads yet!import java. io.*;import java. net.*;public class JabberServer {// Choose a port outside of the range 1- 1024:static final int port = 8080;public static void main( String[] args )

Some Examples Client/Server

Page 65: 1 Week 2 “Just Java” by Linden chapters 4,5,13 Java I/O and Client/Server Some of the material on I/O and client/server is from Bruce Eckel’s “Thinking

65

try { boolean flush = true; ServerSocket s = new ServerSocket(port); System. out. println(" Server Started: " + s); // Blocks until a connection occurs: Socket socket = s.accept(); System. out. println( "Connection accepted, socket: "+ socket); BufferedReader in = new BufferedReader( new InputStreamReader( socket.getInputStream())); PrintWriter out = new PrintWriter( new BufferedWriter( new OutputStreamWriter( socket.getOutputStream())), flush);

Page 66: 1 Week 2 “Just Java” by Linden chapters 4,5,13 Java I/O and Client/Server Some of the material on I/O and client/server is from Bruce Eckel’s “Thinking

66

while (true) { // till client says ‘END’

String str = in.readLine();

if (str.equals("END")) break;

System.out.println(" Echoing: " + str);

out.println(str);

}

System.out.println(" closing...");

socket.close();

} catch( Exception e) {

e.printStackTrace();

}

}

Page 67: 1 Week 2 “Just Java” by Linden chapters 4,5,13 Java I/O and Client/Server Some of the material on I/O and client/server is from Bruce Eckel’s “Thinking

67

// JabberClient. Java from Bruce Eckel’s text// Very simple client that just sends// lines to the server and reads lines that the server sends.

import java. net.*;import java. io.*;public class JabberClient {// Choose a port outside of the range 1- 1024:static final int port = 8080;public static void main( String args[]) {try { // Produce "Local Loopback" IP address InetAddress addr =InetAddress.getByName(null); System.out. println(" addr = " + addr); Socket socket = new Socket(addr, port); // ‘remote’ server System.out.println(" socket = " + socket);

Page 68: 1 Week 2 “Just Java” by Linden chapters 4,5,13 Java I/O and Client/Server Some of the material on I/O and client/server is from Bruce Eckel’s “Thinking

68

BufferedReader in = new BufferedReader( new InputStreamReader( socket.getInputStream()));

// Enable PrintWriter autoflush:

PrintWriter out = new PrintWriter( new BufferedWriter( new OutputStreamWriter( socket. getOutputStream())), flush);

Page 69: 1 Week 2 “Just Java” by Linden chapters 4,5,13 Java I/O and Client/Server Some of the material on I/O and client/server is from Bruce Eckel’s “Thinking

69

for( int i = 0; i < 10; i ++) { out. println(" howdy " + i); String str = in. readLine(); System. out. println( str); } out. println(" END"); } catch( Exception e) { e. printStackTrace(); } }}

Page 70: 1 Week 2 “Just Java” by Linden chapters 4,5,13 Java I/O and Client/Server Some of the material on I/O and client/server is from Bruce Eckel’s “Thinking

70

Lab Problem Discussion

From “Just Java” page 378

Modify the program below (Dump.java) so that it alsooutputs any printable bytes in a set of columns to the right of the hex dump on each line. Print the character if it has a printableform, and print a “.” if it does not. This ensures that lines arethe same length and columns line up.

The program Dump.java is also found on page 371 of “Just Java”.

Page 71: 1 Week 2 “Just Java” by Linden chapters 4,5,13 Java I/O and Client/Server Some of the material on I/O and client/server is from Bruce Eckel’s “Thinking

71

// This program hex dumps the contents of the file // whose name is given as a commandline argument. import java.io.*; public class Dump { static FileInputStream myFIS = null; static FileOutputStream myFOS = null; static BufferedInputStream myBIS = null; static PrintStream myPOS = null;

static public void main(String[] arg) { if (arg.length==0) { System.out.println("usage: java Dump somefile"); System.exit(0); }

Page 72: 1 Week 2 “Just Java” by Linden chapters 4,5,13 Java I/O and Client/Server Some of the material on I/O and client/server is from Bruce Eckel’s “Thinking

72

PrintStream e = System.err; try { myFIS = new FileInputStream( arg[0] ); myFOS = new FileOutputStream( arg[0] + ".hex" );

myBIS = new BufferedInputStream(myFIS); // the "true" says we want writes flushed to disk with // each newline myPOS = new PrintStream ( new BufferedOutputStream(myFOS), true); myPOS.print("Hex dump of file " + arg[0]);

int i; while ( (i=myBIS.read()) != -1 ) { dump( (byte) i ); }

Page 73: 1 Week 2 “Just Java” by Linden chapters 4,5,13 Java I/O and Client/Server Some of the material on I/O and client/server is from Bruce Eckel’s “Thinking

73

} catch(IOException x) { e.println("Exception: " + x.getMessage() ); } }

static private long byteCount = 0;

static private void dump(byte b) { if (byteCount % 16 == 0) { // output newline and the address every 16 bytes myPOS.println();

// pad leading zeros in address. String addr = Long.toHexString(byteCount); while (addr.length() < 8) addr = "0" + addr; myPOS.print( addr + ":" ); }

Page 74: 1 Week 2 “Just Java” by Linden chapters 4,5,13 Java I/O and Client/Server Some of the material on I/O and client/server is from Bruce Eckel’s “Thinking

74

// output a space every 4 bytes if (byteCount++ % 4 == 0) { myPOS.print(" "); }

// dump the byte as 2 hex chars String s = Integer.toHexString( b & 0xFF ); if (s.length()==1) s = "0" + s; myPOS.print( s.charAt(0) ); myPOS.print( s.charAt(1) + " " ); } }