Java Network Programing - Computer Network Programing - Lecture Slide | CSCE 515, Study notes of Computer Science

Material Type: Notes; Professor: Xu; Class: COMPUTR NETWRK PROGRAMNG; Subject: Computer Science & Engineering; University: University of South Carolina - Columbia; Term: Unknown 2007;

Typology: Study notes

Pre 2010

Uploaded on 09/02/2009

koofers-user-lt7-1
koofers-user-lt7-1 🇺🇸

10 documents

1 / 14

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
CSCE 515:
Computer Network
Programming
------ Java Network Programming
reference: Dave Hollinger
Wenyuan Xu
http://www.cse.sc.edu/~wyxu/csce515f07.html
Department of Computer Science and Engineering
University of South Carolina
Java Network Programming
Introduction
Java Socket Programming
InetAddress
Socket
ServerSocket
DatagramSocket
Multicast Socket
CSCE515 – Computer Network Programming2007
Crash Course in Java
Why Java?
Network Programming in Java is very
different than in C/C++
much more language support
error handling
no pointers! (garbage collection)
Threads are part of the language.
some support for common application level
protocols (HTTP).
Netprog: Java Intro 4
Java notes for C++ programmers
Everything is an object.
No code outside of class definition!
Single inheritance
an additional kind of inheritance: interfaces
All classes are defined in .java files
one top level public class per file
To print to stdout:
System.out.println();
Netprog: Java Intro 5
First Program: Simp.java
public class Simp {
public static void main(String args[]) {
System.out.println("Hello, Netprog");
}
}
public class Simp {
public static void main(String args[]) {
System.out.println("Hello, Netprog");
}
}
Netprog: Java Intro 6
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe

Partial preview of the text

Download Java Network Programing - Computer Network Programing - Lecture Slide | CSCE 515 and more Study notes Computer Science in PDF only on Docsity!

CSCE 515:

Computer Network

Programming

------ Java Network Programming

reference: Dave Hollinger Wenyuan Xu

http://www.cse.sc.edu/~wyxu/csce515f07.html Department of Computer Science and Engineering University of South Carolina

Java Network Programming

„ Introduction

„ Java Socket Programming

InetAddress

Socket

ServerSocket

DatagramSocket

„ Multicast Socket

2007 CSCE515 – Computer Network Programming

Crash Course in Java

Why Java?

„ Network Programming in Java is very

different than in C/C++

much more language support

error handling

no pointers! (garbage collection)

Threads are part of the language.

some support for common application level protocols (HTTP).

Netprog: Java Intro^4

Java notes for C++ programmers

„ Everything is an object.

„ No code outside of class definition!

„ Single inheritance

an additional kind of inheritance: interfaces

„ All classes are defined in .java files

one top level public class per file

„ To print to stdout:

System.out.println();

Netprog: Java Intro

5

First Program: Simp.java

public class Simp {

public static void main(String args[]) {

System.out.println("Hello, Netprog");

public class Simp {

public static void main(String args[]) {

System.out.println("Hello, Netprog");

Netprog: Java Intro

6

Compiling and Running

Netprog: Java Intro

7

Simp.java

javac Simp.java

java Simp Simp.class

compile run

bytecode

source code

Java bytecode and interpreter

„ bytecode is an intermediate representation of the program (class).

„ The Java interpreter starts up a new “Virtual Machine”.

„ The VM starts executing the users class by running it’s main() method.

Netprog: Java Intro

8

Java Data Types

„ Primitive Data Types:

boolean true or false

char unicode! (16 bits)

byte signed 8 bit integer

short signed 16 bit integer

int signed 32 bit integer

long signed 64 bit integer

float , double IEEE 754 floating point

Netprog: Java Intro^9

not an int!

Other Data Types

„ Reference types (composite)

classes

arrays

„ strings are supported by a built-in class named String

„ string literals are supported by the language (as a special case).

Netprog: Java Intro^10

Classes and Objects

„ “All Java statements appear within

methods, and all methods are defined

within classes”.

„ Java classes are very similar to C++

classes (same concepts).

„ Instead of a “standard library”, Java

provides a lot of Class implementations.

Netprog: Java Intro

11

Defining a Class

„ One top level public class per .java file.

typically end up with many .java files for a single program.

One (at least) has a static public main() method.

„ Class name must match the file name!

compiler/interpreter use class names to figure out what file name is.

Netprog: Java Intro

12

Packages

„ You can organize a bunch of classes into

a package.

defines a namespace that contains all the classes.

„ You need to use some java packages in

your programs

java.lang java.io, java.util

Netprog: Java Intro

19

Importing classes and packages

„ Instead of #include , you use import

„ You don’t have to import anything, but

then you need to know the complete name

(not just the class, the package).

if you import java.io.File you can use File objects.

If not – you need to use java.io.File objects.

Netprog: Java Intro

20

Exceptions

„ Terminology:

throw an exception : signal that some condition (possibly an error) has occurred.

catch an exception : deal with the error (or whatever).

„ In Java, exception handling is necessary

(forced by the compiler)!

Netprog: Java Intro^21

Try/Catch/Finally

try {

// some code that can throw

// an exception

} catch (ExceptionType1 e1) { // code to handle the exception

} catch (ExceptionType2 e2) {

// code to handle the exception

} finally {

// code to run after the stuff in try

// can handle other exception types } Netprog: Java Intro^22

Exceptions and Network Programming

„ Exceptions take care of handling errors

instead of returning an error, some method calls will throw an exception.

„ A little hard to get used to, but forces the

programmer to be aware of what errors

can occur and to deal with them.

Netprog: Java Intro

23

Socket Programming

Netprog: Java Sockets

25

Java Sockets Programming

„ The package java.net provides support for

sockets programming (and more).

„ Typically you import everything defined in

this package with:

import java.net.;*

Classes

InetAddress

Socket

ServerSocket

DatagramSocket

DatagramPacket

Netprog: Java Sockets

26

java.net.InetAddress class

„ static methods you can use to create new

InetAddress objects. public static InetAdress getByName(String host) public static InetAdress getLocalHost() public static InetAdress[] getAllByName(String hostName)

InetAddress x = InetAddress.getByName(

“cse.sc.edu”);

Netprog: Java Sockets^27

Sample Code: Lookup.java

„ Uses InetAddress class to lookup

hostnames found on command line.

¾ java Lookup www.yahoo.com

www.yahoo.com:209.191.93.

Netprog: Java Sockets^28

Netprog: Java Sockets

29

try {

InetAddress a = InetAddress.getByName(hostname);

System.out.println(hostname + ":" + a.getHostAddress());

} catch (UnknownHostException e) {

System.out.println("No address found for " + hostname);

}

try {

InetAddress a = InetAddress.getByName(hostname);

System.out.println(hostname + ":" + a.getHostAddress());

} catch (UnknownHostException e) {

System.out.println("No address found for " + hostname);

}

Sample Code: getLocalhost.java

„ Uses InetAddress class to lookup

localhost

¾ java getLocalhost

broad/129.252.130.

Netprog: Java Sockets

30

Socket Methods

void close();

InetAddress getInetAddress(); getpeername

InetAddress getLocalAddress(); getsockname

InputStream getInputStream();

OutputStream getOutputStream();

„ Lots more (setting/getting socket options,

partial close, etc.)

Netprog: Java Sockets

37

Socket I/O

„ Socket I/O is based on the Java I/O

support (in the package java.io ).

„ InputStream and OutputStream are

abstract classes

common operations defined for all kinds of InputStreams, OutputStreams…

Netprog: Java Sockets

38

InputStream Basics

// reads some number of bytes and

// puts in buffer array b

int read(byte[] b);

// reads up to len bytes

int read(byte[] b, int off, int len);

Both methods can throw IOException.

Both return –1 on EOF.

Netprog: Java Sockets^39

OutputStream Basics

// writes b.length bytes

void write(byte[] b);

// writes len bytes starting

// at offset off void write(byte[] b, int off, int len);

Both methods can throw IOException.

Netprog: Java Sockets^40

Output stream example

2007 CSCE515 – Computer Network Programming

InetAddress myServerAddr; Socket MyClient;

DataOutputStream output;

try { … output = new DataOutputStream(MyClient.getOutputStream()); output.writeBytes(“hello”); output.writeBytes("DATA\n"); } catch (IOException e) { System.out.println(e); }

InetAddress myServerAddr; Socket MyClient;

DataOutputStream output;

try { … output = new DataOutputStream(MyClient.getOutputStream()); output.writeBytes(“hello”); output.writeBytes("DATA\n"); } catch (IOException e) { System.out.println(e); }

Sample Client

„ smtpClient.java

„ Simple client code to send an email via an smtp server

„ Client:

Open a socket.

Open an input and output stream to the socket.

Read from and write to the socket according to the server's protocol.

Clean up.

2007 CSCE515 – Computer Network Programming

ServerSocket Class –Servers

(TCP Passive Socket)

„ Constructors:

ServerSocket(int port);

ServerSocket(int port, int backlog);

ServerSocket(int port, int backlog,

InetAddress bindAddr);

Netprog: Java Sockets

43

ServerSocket Constructors

ServerSocket(int port, int backlog);

Netprog: Java Sockets

44

ServerSocket MyService;

try { MyService = new ServerSocket(PortNumber, 90);

} catch (IOException e) { System.out.println(e); }

ServerSocket MyService;

try { MyService = new ServerSocket(PortNumber, 90);

} catch (IOException e) { System.out.println(e); }

ServerSocket Methods

Socket accept();

void close();

InetAddress getInetAddress();

int getLocalPort();

throw IOException, SecurityException

Netprog: Java Sockets^45

Sample Echo Server

„ TCPEchoServer.java

„ Server:

1. Create a ServerSocket

2. accept incoming request, get a Socket

3. Open an input and output stream to the Socket.

4. Read from and write to the Socket according to the

server's protocol.

5. Close the Socket

6. Return to step 2

Netprog: Java Sockets^46

UDP Sockets

„ DatagramSocket class

„ DatagramPacket class needed to specify

the payload (incoming or outgoing).

Netprog: Java Sockets

47

DatagramSocket Constructors

DatagramSocket();

DatagramSocket(int port);

DatagramSocket(int port, InetAddress a);

All can throw SocketException or SecurityException.

When should each constructors be used?

Netprog: Java Sockets

48

Sample UDP code

UDPEchoServer.java

Simple UDP Echo server.

Test using nc as the client (netcat):

> nc –u hostname port

Netprog: Java Sockets

55

Multicast

2007

CSCE515 – Computer Network Programming

Multicasting

„ Unicast

A flow from one source to one destination

IP packets contain destination IP address

„ Broadcast

A flow from one source to all destinations

IP packets contain broadcast address 255.255.255.

„ Multicast

A flow from one source transmits to a Group of destinations

IP packets contain a class D address for destination

Ranges from 224.0.0.0 to 239.255.255.255 (256K addresses)

2007 CSCE515 – Computer Network Programming

Multicast vs. Multiple Unicast

2007 CSCE515 – Computer Network Programming

Advantages of Multicasting

„ Advantages:

Lower overhead at the source „ Source sends only one packet

Bandwidth is conserved on shared links „ Only one copy of each packet is sent on each link

„ Requirements:

Group address management „ – Network/router participation

Packet duplication at routing nodes

„ Disadvantages

Security

Business models

No Incentives for deployment

2007 CSCE515 – Computer Network Programming

Multicast Addressing

The set of hosts listening to a particular multicast address is called a host group

Multicast packets, at least for now, are sent only as UDP packets (WHY?)

Some of the addresses 224.0.0.0 to 224.0.0.15 are reserved for well-known groups 239.0.0.0 to 239.255.255.255 are for local/administratively scoped applications

Like any IP address, a multicast address can have a hostname, e.g. 224.0.0.2 -- all-routers.mcast.net (All routers on the local subnet)

2007 CSCE515 – Computer Network Programming

Class D 1 1 1 0 multicast group ID

Mapping to Ethernet Addresses

„ Ethernet has a 48-bit address field

It has its own multicast address range

01.00.5e.00.00.00 through 01.00.5e.7f.ff.ff

„ Lower order 23 bits can be used for multicast addresses

IP multicast address has 28 bits for specifying a group address

Thus, only the lower order 23 bits of IP multicast address are copied into the Ethernet address

2007 CSCE515 – Computer Network Programming

Link-Layer Multicast Addresses

„ Ranges from 01:00:5E:00:00:00 to 01:00:5E:FF:FF:FF

Map low-order 23 bits of class D address to lower order 23 bits of ethernet multicast address space

Upper 5 bits of multicast group ID are ignored in the mapping, thus mapping is not unique

„ For point-to-point links: no mapping needed.

2007 CSCE515 – Computer Network Programming

Multicast service model

„ Uses the notion of host groups

Sender sends to a group address

Any receiver who has joined this group gets this packets

„ Implications?

No limits on number or location of receivers

Best effort delivery (same as in unicast)

„ Dynamic membership

Host can join/leave at will (no synchronization required among group members)

„ Scope control

Can limit the distribution using TTL

2007 CSCE515 – Computer Network Programming

Components of the IP Multicast Architecture

2007 CSCE515 – Computer Network Programming

Multicast Routers

„ Biggest restriction on multicasting:

Availability of special multicast routers

„ Check whether your routers support

multicasting: wyxu@broad % ping all-routers.mcast.net all-routers.mcast.net is alive

2007 CSCE515 – Computer Network Programming

IGMP

„ Internet Group Management Protocol (IGMP)

„ Allows a router to know which of its directly connected

hosts belongs to which multicast group

„ IGMP is required to support TRPB, RPM, CBT and PIM

protocols

2007 CSCE515 – Computer Network Programming

73 2/17/

Class MulticastSocket

„ Extend class DatagramSocket and add

support for IP multicast

„ Multiple MulticastSockets can listen to

same port on same machine

„ Constructors

MulticastSocket()

MulticastSocket(int port)

MulticastSocket(SocketAddress

bindAddress)

74 2/17/

Class MulticastSocket

try {

MulticastSocket ms = new MulticastSocket(); //send some datagrams

} catch (SocketException e) {

System.out.println(e);

}

try {

MulticastSocket ms = new MulticastSocket(); //send some datagrams

} catch (SocketException e) {

System.out.println(e);

}

75 2/17/

Class MulticastSocket

Methods void joinGroup(InetAddress group) throws IOException void leaveGroup(InetAddress group) throws IOException void setTimeToLive(int ttl) throws IOException void setTTL(byte ttl) throws IOException int getTimeToLive() throws IOException byte getTTL() throws IOException void send(DatagramPacket packet, byte ttl) throws IOException void setInterface(InetAddress address) throws SocketException InetAddress getInterface() throws SocketException

Exceptions IOException SecurityException

76 2/17/

Sending Multicast Packets

// byte[] data // InetAddress multicastGroup // int multicastPort MulticastSocket socket = new MulticastSocket();

DatagramPacket packet = new DatagramPacket (data, data.length, multicastGroup, multicastPort);

socket.send(packet, (byte) 64);

socket.close();

77 2/17/

Receiving Multicast Packets

MulticastSocket socket = new MulticastSocket(multicastPort); Socket.joinGroup(multicastGroup);

byte buffer[] = new byte[65508]; DatagramPacket packet = new DatagramPacket();

socket.receive(packet);

InetAddress fromAddress = packet.getAddress(); int fromPort = packet.getPort(); int length = packet.getLength(); byte[] data = packet.getData(); // …

socket.leaveGroup(multicastGroup); socket.close();

Sample MulticastSocket code

MulticastSender.java

MulticastSniffer.java

Receiver:

Broad % java MulticastSniffer all- systems.mcast.net 4000

Sender:

Broad % java MulticastSender all- systems.mcast.net 4000

Netprog: Java Sockets

78

79 2/17/

A Peer-to-Peer Multicast Chat System

„ Each client multicasts its message to other

clients

„ No server is involved; all clients

communicate as peers

„ Open a chat frame and start a thread that

listens for incoming packets