Chapter 6 Network Programming

Download as pdf or txt
Download as pdf or txt
You are on page 1of 91

Overview

0 Java’s network support


0 Addressing other machines
0 Communicating using TCP/IP
0 Communicating using UDP
0 Broadcasting and multicasting

AP : Network Prog. 2
Network Programming
0 Network programming is a mechanisms by which software
running on two or more computational devices can exchange
messages
0 Desktop Computers, PDAs / Set Top Boxes / Mobile Telephones
0 Java is a network centric programming language
0 Java abstracts details of network implementation behind a
standard API

AP : Network Prog. 3
A programming model for
network communications
Java APIs Applications

HTTP/FTP/etc... Application Protocols

1:1 or 1:Many Unicast Broadcast Multicast


Streams
TCP, UDP Datagrams

Internet Protocol Addressing & Routing

Java & IP don’t care Physical Transport

AP : Network Prog. 4
Networking Basics
0 Applications Layer
0 Standard apps TCP/IP Stack
0 HTTP
0 FTP Application
0 Telnet (http,ftp,telnet,…)
0 User apps
0 Transport Layer Transport
0 TCP (TCP, UDP,..)
0 UDP Network
0 Programming Interface: (IP,..)
0 Sockets
0 Network Layer Link
0 IP (device driver,..)
0 Link Layer
0 Device drivers
AP : Network Prog. 5
Networking Basics
0 TCP (Transport Control TCP/IP Stack
Protocol) is a connection-
oriented protocol that Application
provides a reliable flow of (http,ftp,telnet,…)
data between two
Transport
computers. (TCP, UDP,..)
0 Example applications: Network
0 HTTP (IP,..)
0 FTP
Link
0 Telnet (device driver,..)

AP : Network Prog. 6
Networking Basics
0 UDP (User Datagram TCP/IP Stack
Protocol) is a protocol that
sends independent packets Application
of data, called datagrams, (http,ftp,telnet,…)
from one computer to
Transport
another with no (TCP, UDP,..)
guarantees(unreliable)
Network
about arrival. (IP,..)
0 Example applications:
Link
0 Clock server (device driver,..)
0 Ping

AP : Network Prog. 7
Understanding Ports
0 The TCP and UDP P
protocols use ports to map o TCP
server
r Client
incoming data to a t
particular process running
on a computer.

app app app app

port port port port

TCP or UDP
Packet
AP : Network Prog. 8
Data port# data
Understanding Ports
0 Port is represented by a positive (16-bit) integer value
0 Some ports have been reserved to support
common/well known services:
0 Port 513 login
0 Ports 20/21 File Transfer Protocol
0 Port 23 Telnet
0 Port 25 Simple Mail Transport Proto.
0 Port 79 Finger
0 Port 80 HTTP
0 Port 110 POP3 (Post Office Protocol)
0 All well known ports in the range 1..1023
0 So user level process/services generally use port
number value >= 1024
AP : Network Prog. 9
Client-Server Architecture
0 Sometimes an application’s structure takes on a client-server nature.
0 A server application provides services such as access to a database,
serving network time, authentication and access to shared resources
or serving out chat conversations.
0 Client applications are then created which make use of these
services.
0 To initiate a point-to-point client-server connection, the
Transmission Control Protocol is used.
0 TCP is a “reliable” protocol – in other words, it guarantees the
delivery of the data it transmits in the form of “packets”. If packet are
lost or damaged, TCP will resend the data until it verifies that
packets have been successfully transmitted.
0 TCP is needed for applications that must reliably send messages
back and forth or initiate file transfers to ensure that a perfect copy
of the data arrives at the other side uncorrupted.
AP : Network Prog. 10
Client-Server Architecture
TCP/IP Sockets
0 When establishing connectivity, the client and server each bind
a “socket” to their end of the connection.
0 Once a connection has been established the client and server
both read from and write to the socket when communicating.
0 A socket is a combination of both an IP address and a port
number.
0 Each socket used in client-server communication is an
endpoint of the two-way communication link used to send
packets between applications.
0 Multiple TCP connections can be initiated between each client
and server and each connection is unique by its combination of
ports and endpoints.
AP : Network Prog. 11
Client-Server Architecture
0 A server runs on a specific host where it creates and
continuously listens to a “server socket” that is bound to a
specified port number and waits for clients to make connection
requests.
0 The client must know the correct port and ip address or
hostname of the server to initiate a connection request and
identify itself .
0 When the server accepts the client’s connection request, the
client also creates a socket and communication between client
and server takes place as both read from and write to their
sockets.
0 Java uses the Socket and ServerSocket classes from the
java.net packege to implement client-server communication
AP : Network Prog. 12
Client-Server Architecture
0 The server application, once a ServerSocket has been
instantiated with a designated port, a new Socket is created to
accept the ServerSocket’s connection request by calling the
accept() method on the ServerSocket object.
0 The InputStreamReader, BufferedReader and PrintStream
class objects are instantiated.
0 The BufferedReader object’s readLine() method is used to
retrive input from the client and the PrintStream object’s
println() method is used to send output to the client.

AP : Network Prog. 13
Client-Server Architecture
0 In the client application a new Socket is created if the server’s
ServerSocket accepts the connection request.
0 The connection is requested by instantiating a Socket class
object and passing in the server’s IP address or hostname and
the selected port as arguments.
0 Then InputStreamReader, BufferedReader and PrintStream
class objects are instantiated.
0 The BufferedReader object’s readLine() method is used to
retrive input from the server and the PrintStream object’s
println() method is used to send output to the servrver.

AP : Network Prog. 14
Client / Server Model
0 Client/Server model is a relationship between two
computer programs
0 Client
0 Initiates communication Client
0 Requests services Server
0 Server Client
0 Receives communication
0 Provides services Client
0 Other models
Server
0 Master / worker Client
0 Peer-to-peer (P2P)
AP : Network Prog. 15
Elements of Client -Server
Computing
a client, a server, and network

Client
Server
Network

Client machine
Server machine
AP : Network Prog. 16
Client / Server Model Examples
Application Client Server

Web Browsing Internet Explorer, Apache


Mozilla Firefox

Email MS Outlook, POP, IMAP, SMTP,


Thunderbird Exchange

Streaming Windows Media Internet Radio


Music Player, iTunes

Online Gaming Half-Life, Everquest, Game / Realm


PartyPoker Servers

AP : Network Prog. 17
Java Networking API
0 Application Program Interface
0 Set of routines, protocols, tools
0 For building software applications
0 Java networking API
0 Helps build network applications
0 Interfaces to sockets, network resources
0 Code implementing useful functionality
0 Includes classes for
0 Sockets
0 URLs

AP : Network Prog. 18
Java Networking Classes
0 IP addresses
0 InetAddress
0 Packets
0 DatagramPacket
0 Sockets
0 Socket
0 ServerSocket
0 DatagramSocket
0 URLs
0 URL

AP : Network Prog. 19
Internet Protocol (IPv4)
0 Abstracts away the details of the physical network
implementations (such as Ethernet, Token Ring, ATM, Sonet)
0 All traffic uses the same rules to move from machine to machine
0 Easy to write programs
0 Easy to build network hardware
0 Works with Datagrams: small discrete packets of data (rather
like a letter)
0 A way of uniquely addressing machines using 32 bit addresses:
giving 4 billion possible addresses.
0 A system for numbering ports on each machine (like a post office
box)
0 Port numbers allow several services to operate from a machine
at the same time
AP : Network Prog. 20
Internet Addresses
 Every computer on the Internet is identified by a unique, four-byte IP address.
 This is typically written in dotted quad format like 199.1.32.90 where each byte is
an unsigned value between 0 and 255.
 Java's java.net.InetAddress class represents such an address.
0 InetAddress getByName(String host) throws
UnknownHostException
0 InetAddress[] getAllByName(String host) throws
UnknownHostException
0 InetAddress getLocalHost() throws UnknownHostException
0 boolean isMulticastAddress()
0 String getHostName()
0 byte[] getAddress()
0 String getHostAddress()
0 int hashCode()
0 boolean equals(Object obj)
0 String toString()
AP : Network Prog. 21
Internet Addresses
0 boolean equals(Object obj)
 compares two IP addresses, returns true if there is a match.
0 byte[ ] getAddress( )
 returns the IP address in byte format.
0 static InetAddress [ ] getAllByName (String hostname) throws
java.net.UnknownHostException, java.lang.SecurityException
 returns an array of InetAddress instances representing the
hostname.
0 static InetAddress getByName (String hostname) throws
java.net.UnknownHostException, java.lang.SecurityException
 returns an InetAddress instance representing the hostname.

AP : Network Prog. 22
Internet Addresses
0 String getHostAddress( )
0 returns the IP address in dotted decimal format.
0 static InetAddress getLocalHost ( ) throws
java.net.UnknownHostException, java.lang.SecurityException
0 returns the IP address of the localhost machine.
0 String getHostName( ) throws java.lang.SecurityManager
0 returns the hostname of the InetAddress.
0 boolean isMulticastAddress( )
0 returns true if the InetAddress is a multicast address (class D
address).

AP : Network Prog. 23
Parsing InetAddressess
0 You can ask InetAddress object for its host name as a string, its IP address as
a string, its IP address as a byte array, and whether or not it's a multicast
address.
try {
InetAddress me = InetAddress.getLocalHost();
System.out.println("My name is " + me.getHostName());
System.out.println("My address is "+ me.getHostAddress());
byte[] address = me.getAddress();
for (int i = 0; i < address.length; i++) {
System.out.print(address[i] + " ");
}
} catch (UnknownHostException e) {
System.err.println("Could not determine local address.");
} Output
My name is My-PC
My address
AP : NetworkisProg.
10.140.160.201 24
10 -116 -96 -55
Working with URLs(Uniform Resource
Locators)
0 URL is a reference (an address) to a resource on the Internet.
0 Java programs can use a class called URL in the java.net package to
represent a URL address.
0 A URL has two main components:
0 Protocol identifier
0 Resource name
0 The protocol identifier indicates the name of the protocol to be
used to fetch the resource. E.g. file ,ftp, gopher, http, mailto
0 The resource name is the complete address to the resource. The
format of the resource name depends entirely on the protocol
used.

AP : Network Prog. 25
The resource name may contain:
Host Name The name of the machine on which the resource lives.

Filename The pathname to the file on the machine.

Port Number The port number to which to connect (typically optional).

A reference to a named anchor within a resource that


Reference usually identifies a specific location within a file (typically
optional).

http://www.ju.edu.et:80/colleges/index.html#cet

AP : Network Prog. 26
URL constructors
0 URL(String url)
0 URL(URL baseURL, String relativeURL)
0 URL(String protocol, String hostName,
String filename)
0 URL(String protocol, String hostName, int
port, String filename)
0 Each constructors throws a MalformedURLException if
the arguments to the constructor refer to a null or unknown
protocol
0 Note: URLs are "write-once" objects. Once you've created a
URL object, you cannot change any of its attributes (protocol,
host name, filename, or port number).

AP : Network Prog. 27
Creating a URL
URL gamelan = new URL("http://www.gamelan.com/");
URL gamelan = new URL("http", "www.gamelan.com",
"/pages/Gamelan.net.html");
URL gamelan = new URL("http", "www.gamelan.com", 80,
"pages/Gamelan.network.html");

0 The URL object created above represents an absolute URL. An absolute


URL contains all of the information necessary to reach the resource in
question. You can also create URL objects from a relative URL address
0 A relative URL contains only enough information to reach the resource
relative to (or in the context of) another URL.
URL gamelan = new URL("http://www.gamelan.com/pages/");
URL gamelanGames = new URL(gamelan,
"Gamelan.game.html");
URL gamelanNetworkBottom = new URL(gamelanGames,
"#BOTTOM"); AP : Network Prog. 28
Parsing a URL
 The URL class provides several methods that let you query URL
objects.(each returns String)
 getProtocol () : Returns the protocol identifier component of the
URL.
 getAuthority () : Returns the authority component of the URL.
 getHost () : Returns the host name component of the URL.
 getPort () : Returns the port number component of the URL. If the
port is not set, getPort returns -1.
 getPath () : Returns the path component of this URL.
 getQuery () : Returns the query component of this URL.
 getFile () : Returns the filename component of the URL. The getFile
method returns the same as getPath, plus the concatenation of the
value of getQuery, if any.
 getRef () : Returns the reference component of the URL

AP : Network Prog. 29
Parsing a URL
import java.net.*;
import java.io.*;
public class ParseURL {
public static void main(String[] args) throws Exception {
URL aURL = new URL("http://java.sun.com:80/docs/books/tutorial"
+ "/index.html?name=networking#DOWNLOADING");
System.out.println("protocol = " + aURL.getProtocol()); // http
//java.sun.com:80
System.out.println("authority = " + aURL.getAuthority());
System.out.println("host = " + aURL.getHost()); //java.sun.com
System.out.println("port = " + aURL.getPort()); // 80
//.. /docs/books/tutorial/index.html
System.out.println("path = " + aURL.getPath());
System.out.println("query = " + aURL.getQuery());//
name=networking
//.. /docs/books/tutorial/index.html?name=networking
System.out.println("filename = " + aURL.getFile());
System.out.println("ref = " + aURL.getRef()); // DOWNLOADING
} AP : Network Prog. 30
}
Parsing a URL
Output
protocol = http
authority = java.sun.com:80
host = java.sun.com
port = 80
path = /docs/books/tutorial/index.html
query = name=networking
filename =
/docs/books/tutorial/index.html?name=networking
ref = DOWNLOADING

AP : Network Prog. 31
Reading Directly from a URL
import java.net.*;
import java.io.*;

public class URLReader {


public static void main(String[] args) throws Exception {
URL yahoo = new URL("http://www.yahoo.com/");
BufferedReader in = new BufferedReader(new InputStreamReader(
yahoo.openStream()));
String inputLine;
while ((inputLine = in.readLine()) != null)
System.out.println(inputLine);
in.close();
}
}
AP : Network Prog. 32
Connecting to a URL using URLConnection

0 you can call the URL object's openConnection


method to get a URLConnection object
0 You can use this URLConnection object to setup
parameters and general request properties that you
may need before connecting.
0 Connection to the remote object represented by the
URL is only initiated when the
URLConnection.connect method is called.
0 When you do this you are initializing a communication
link between your Java program and the URL over the
network.

AP : Network Prog. 33
Connecting to a URL
try {
URL yahoo = new URL("http://www.yahoo.com/");
URLConnection yahooConnection =
yahoo.openConnection();
yahooConnection.connect();

} catch (MalformedURLException e) {
// new URL() failed
. . .
} catch (IOException e) {
// openConnection() failed
}
0 You are not always required to explicitly call the connect method to initiate the
connection. Operations that depend on being connected, like getInputStream,
getOutputStream, etc, will implicitly perform the connection, if necessary.

AP : Network Prog. 34
Reading from and Writing to a URLConnection

0 The URLConnection class contains many methods that


let you communicate with the URL over the network.
0 URLConnection is an HTTP-centric class; that is, many
of its methods are useful only when you are working
with HTTP URLs.
0 However, most URL protocols allow you to read from
and write to the connection.

AP : Network Prog. 35
Reading from a URLConnection
import java.net.*;
import java.io.*;

public class URLConnectionReader {


public static void main(String[] args) throws Exception {
URL yahoo = new URL("http://www.yahoo.com/");
URLConnection yc = yahoo.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(
yc.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null)
System.out.println(inputLine);
in.close();
} }
 Reading from a URLConnection instead of reading directly from a URL might be more useful,
because you can use the URLConnection object for other tasks (like writing to the URL) at the
same time
AP : Network Prog. 36
Writing to a URLConnection
 For a Java program to interact with a server-side process it
simply must be able to write to a URL, thus providing data
to the server.
 It can do this by following these steps:
 Create a URL.
 Retrieve the URLConnection object.
 Set output capability on the URLConnection.
 Open a connection to the resource.
 Get an output stream from the connection.
 Write to the output stream.
 Close the output stream.

AP : Network Prog. 37
Writing to a URLConnection
import java.io.*;
import java.net.*;
public class Reverse {
public static void main(String[] args) throws Exception {
String stringToReverse = URLEncoder.encode(“Reverse Me”, "UTF-8");
URL url = new URL(“http://foobar.com/servlet/ReverseServlet ”);
URLConnection connection = url.openConnection();
connection.setDoOutput(true);
OutputStreamWriter out = new
OutputStreamWriter(connection.getOutputStream());
out.write("string=" + stringToReverse);
out.close();
BufferedReader in = new BufferedReader(new
InputStreamReader(connection.getInputStream()));
String decodedString;
while ((decodedString = in.readLine()) != null) {
System.out.println(decodedString);
}
in.close();
} }
AP : Network Prog. 38
IP Addresses and Java
0 Java has a class java.net.InetAddress which
abstracts network addresses
0 This class serves three main purposes:
0 Encapsulates an address
0 Performs name lookup (converting a host name into an
IP address)
0 Performs reverse lookup (converting the address into a
host name)

AP : Network Prog. 39
Transmission Control Protocol
0 TCP is built on top of IP
0 Provides the illusion of a continuous flow (or stream) of data between
sender and receiver (rather like a telephone call)
0 Splits up streams into strings of small datagrams which are sent in
succession
0 Contains an error recovery mechanism to recover datagrams which are
lost
0 These features make application development simpler and so it is widely
used
0 Used by FTP / Telnet / Finger and numerous other network
applications
0 Used by stream oriented servers such as HTTP
0 Can also be used to provide inter-process communications (IPC)
between the applications on a single machine (such as a X-windows
clients and servers)
AP : Network Prog. 40
Socket programming with TCP
Client must contact server 0 When client creates socket:
0 server process must first be client TCP establishes
running connection to server TCP
0 server must have created 0 When contacted by client, server
socket (door) that welcomes TCP creates new socket for
client’s contact server process to communicate
with client
Client contacts server by:
0 allows server to talk with
0 creating client-local TCP socket
multiple clients
0 specifying IP address, port
number of server process application viewpoint
TCP provides reliable, in-order
transfer of bytes (“pipe”)
between client and server
AP : Network Prog. 41
TCP - Connection Oriented
0 TCP Protocol

AP : Network Prog. 42
Two types of TCP Socket
0 java.net.ServerSocket is used by servers so
that they can accept incoming TCP/IP connections
0 A server is a piece of software which advertises and then
provides some service on request
0 java.net.Socket is used by clients who wish to
establish a connection to a (remote) server
0 A client is a piece of software (usually on a different
machine) which makes use of some service

AP : Network Prog. 43
java.net.ServerSocket (1)

0 Listens on well-known port for incoming connections


0 Creates a dynamically allocated port for each newly
established connection
0 Provides a Socket connected to the new port
0 Maintains a queue to ensure that prospective clients
are not lost

AP : Network Prog. 44
java.net.ServerSocket (2)
0 Construction:
0 ServerSocket(int port, int backlog)
0 Allows up to backlog(many) requests to queue waiting for the
server to deal with them
0 Some useful methods:
0 Socket accept()
0 Blocks waiting for a client to attempt to establish a connection
0 void close()
0 Called by the server when it is shutting down to ensure that any
resources are deallocated

AP : Network Prog. 45
java.net.Socket (1)
0 Provides access to TCP/IP streams
0 Bi-directional communication between sender and
receiver
0 Can be used to connect to a remote address and port
by using the constructor:
0 Socket(String remoteHost, int port)
0 Also used to accept an incoming connection

AP : Network Prog. 46
java.net.Socket (2)
0 Can obtain access to input and output streams
0 Input stream allows reception of data from the other
party
0 InputSteam getInputStream()
0 Output stream allows dispatch(send) of data to the
other party
0 OutputStream getOutputStream()

AP : Network Prog. 47
Implementing a Server
1. Open the Server Socket:
ServerSocket server;
server = new ServerSocket( PORT );
DataOutputStream os;
DataInputStream is;
2. Wait for the Client Request:
Socket client = server.accept();
3. Create I/O streams for communicating to the client
is = new DataInputStream( client.getInputStream() );
os = new DataOutputStream( client.getOutputStream() );
4. Perform communication with client
Receive from client: String line = is.readLine();
Send to client: os.writeBytes("Hello\n");
5. Close sockets: client.close();
For multithreaded server:
while(true) {
i. wait for client requests (step 2 above)
ii. create a thread with “client” socket as parameter (the thread creates streams (as
in step (3) and does communication as stated in (4). Remove thread once service
is provided.
} AP : Network Prog. 48
Implementing a Client
1. Create a Socket Object:
client = new Socket( server, port_id );
2. Create I/O streams for communicating with the server.
is = new DataInputStream(client.getInputStream() );
os = new DataOutputStream( client.getOutputStream() );
3. Perform I/O or communication with the server:
0 Receive data from the server:
String line = is.readLine();
0 Send data to the server:
os.writeBytes("Hello\n");
4. Close the socket when done:
client.close();

AP : Network Prog. 49
Example: Java server (TCP)
import java.io.*;
import java.net.*;

class TCPServer {

public static void main(String argv[]) throws Exception


{
String clientSentence;
Create String capitalizedSentence;
welcoming socket
ServerSocket welcomeSocket = new ServerSocket(6789);
at port 6789
while(true) {
Wait, on welcoming
socket for contact Socket connectionSocket = welcomeSocket.accept();
by client
BufferedReader inFromClient =
Create input new BufferedReader(new
stream, attached InputStreamReader(connectionSocket.getInputStream()));
to socket
AP : Network Prog. 50
Example: Java server (TCP), cont
Create output
stream, attached DataOutputStream outToClient =
to socket new DataOutputStream(connectionSocket.getOutputStream());
Read in line
from socket clientSentence = inFromClient.readLine();

capitalizedSentence = clientSentence.toUpperCase() + '\n';


Write out line
outToClient.writeBytes(capitalizedSentence);
to socket
}
}
} End of while loop,
loop back and wait for
another client connection

AP : Network Prog. 51
Example: Java client (TCP)
import java.io.*;
import java.net.*;
class TCPClient {

public static void main(String argv[]) throws Exception


{
String sentence;
String modifiedSentence;
Create
input stream BufferedReader inFromUser =
new BufferedReader(new InputStreamReader(System.in));
Create
client socket, Socket clientSocket = new Socket("hostname", 6789);
connect to server
Create DataOutputStream outToServer =
output stream new DataOutputStream(clientSocket.getOutputStream());
attached to socket

52
AP : Network Prog.
Example: Java client (TCP), cont.
Create BufferedReader inFromServer =
input stream new BufferedReader(new
attached to socket InputStreamReader(clientSocket.getInputStream()));

sentence = inFromUser.readLine();
Send line
to server outToServer.writeBytes(sentence + '\n');

Read line modifiedSentence = inFromServer.readLine();


from server
System.out.println("FROM SERVER: " + modifiedSentence );

clientSocket.close();

}
}

AP : Network Prog. 53
Socket Exceptions
try {
Socket client = new Socket(host, port);
handleConnection(client);
}
catch(UnknownHostException uhe) {
System.out.println("Unknown host: " + host);
uhe.printStackTrace();
}
catch(IOException ioe) {
System.out.println("IOException: " + ioe);
ioe.printStackTrace();
}

AP : Network Prog. 54
ServerSocket & Exceptions
0 public ServerSocket(int port) throws IOException
0 Creates a server socket on a specified port.
0 A port of 0 creates a socket on any free port. You can use
getLocalPort() to identify the (assigned) port on which this
socket is listening.
0 The maximum queue length for incoming connection
indications (a request to connect) is set to 50. If a connection
indication arrives when the queue is full, the connection is
refused.
0 Throws:
0 IOException - if an I/O error occurs when opening the socket.
0 SecurityException - if a security manager exists and its
checkListen method doesn't allow the operation.

AP : Network Prog. 55
Client/server socket interaction: TCP
Server (running on hostid) Client
create socket,
port=x, for
incoming request:
welcomeSocket =
ServerSocket()

TCP create socket,


wait for incoming
connection request connection setup connect to hostid, port=x
connectionSocket = clientSocket =
welcomeSocket.accept() Socket()

send request using


read request from clientSocket
connectionSocket

write reply to
connectionSocket read reply from
clientSocket
close
connectionSocket close
AP : Network Prog. clientSocket 56
What are datagrams?
0 Datagrams are discrete packets of data
0 Each is like a parcel that can be addressed and sent to
an recipient anywhere on the Internet
0 This is abstracted as the User Datagram Protocol
(UDP) in RFC768
0 Most networks cannot guarantee reliable delivery of
datagrams

AP : Network Prog. 57
Why use datagrams?
0 Good for sending data that can naturally be divided
into small chunks
0 Poor for (lossless) stream based communications
0 Makes economical use of network bandwidth (up to 3
times the efficiency of TCP/IP for small messages)
0 Datagrams can be locally broadcast or multicast (one-
to-many communication)

AP : Network Prog. 58
Socket Programming with
UDP
0 UDP
0 Connectionless and unreliable service.
0 There isn’t an initial handshaking phase.
0 Doesn’t have a pipe.
0 transmitted data may be received out of order, or lost

0 Socket Programming with UDP


0 No need for a welcoming socket.
0 No streams are attached to the sockets.
0 the sending hosts creates “packets” by attaching the IP
destination address and port number to each batch of bytes.
0 The receiving process must unravel(untie) to received packet to
obtain the packet’s information bytes.
AP : Network Prog. 59
JAVA UDP Sockets
0 In Package java.net
0 java.net.DatagramSocket
0 A socket for sending and receiving datagram packets.
0 Constructor and Methods
0 DatagramSocket(int port): Constructs a datagram socket
and binds it to the specified port on the local host machine.
0 void receive( DatagramPacket p)
0 void send( DatagramPacket p)
0 void close()

AP : Network Prog. 60
Socket programming with UDP
UDP: no “connection” between
client and server
0 no handshaking
0 sender explicitly attaches IP application viewpoint
address and port of destination
UDP provides unreliable transfer
0 server must extract IP address,
of groups of bytes (“datagrams”)
port of sender from received
between client and server
datagram
UDP: transmitted data may be
received out of order, or lost

AP : Network Prog. 61
Client/server socket interaction: UDP
Server (running on hostid) Client

create socket, create socket,


port=x, for clientSocket =
incoming request: DatagramSocket()
serverSocket =
DatagramSocket()
Create, address (hostid, port=x),
send datagram request
read request from using clientSocket
serverSocket

write reply to
serverSocket
specifying client read reply from
host address, clientSocket
port number close
clientSocket

AP : Network Prog. 62
UDP - Packet Oriented
0 UDP Protocol

AP : Network Prog. 63
Application using datagrams
0 UDP can be used for economical point-to-point
communications over LANs
0 Unix NFS (Network File System)
0 NIS (a.k.a. Yellow Pages)
0 Datagrams can be used for one-to-many
communication:
0 Local network broadcasting;
0 Multicasting (MBONE)
0 but there is no way to create one-to-many streams
using TCP/IP

AP : Network Prog. 64
java.net.DatagramPacket (1)
0 DatagramPackets normally used as short lived envelopes
for datagram messages:
0 Used to assemble messages before they are dispatched onto
the network,
0 or dismantle(disassemble) messages after they have been
received
0 Has the following attributes:
0 Destination/source address
0 Destination/source port number
0 Data bytes constituting the message
0 Length of message data bytes

AP : Network Prog. 65
java.net.DatagramPacket (2)
0 Construction:
0 DatagramPacket(byte[] data, int length)
0 Some useful methods:
0 void setAddress(InetAddress addr)
0 InetAddress getAddress()
0 void setPort(int port)
0 int getPort()
0 DatagramPackets are not immutable so, in principle
you can reuse them .

AP : Network Prog. 66
java.net.DatagramSocket (1)
0 Used to represent a socket associated with a specific
port on the local host
0 Used to send or receive datagrams
0 Note: there is no counterpart to
java.net.ServerSocket! Just use a
DatagramSocket with a agreed port number so others
know which address and port to send their datagrams
to

AP : Network Prog. 67
java.net.DatagramSocket (2)
0 Construction:
0 DatagramSocket(int port)
0 Uses a specified port (used for receiving datagrams)
0 DatagramSocket()
0 Allocate any available port number (for sending)
0 Some useful methods:
0 void send(DatagramPacket fullPacket)
0 Sends the full datagram out onto the network
0 void receive(DatagramPacket emptyPacket)
0 Waits until a datagram and fills in emptyPacket with the
message

AP : Network Prog. 68
DatagramSender
0 This example sends datagrams to a specific host
(anywhere on the Internet)
0 The steps are as follows:
0 Create a new DatagramPacket
0 Put some data which constitutes your message in the
new DatagramPacket
0 Set a destination address and port so that the network
knows where to deliver the datagram
0 Create a socket with a dynamically allocated port
number (if you are just sending from it)
0 Send the packet through the socket onto the network

AP : Network Prog. 69
DatagramSender
byte[] data = “This is the message”.getBytes();
DatagramPacket packet =
new DatagramPacket(data, data.length);

// Create an address
InetAddress destAddress =
InetAddress.getByName(“somesite.domain.com”);
packet.setAddress(destAddress);
packet.setPort(9876);

DatagramSocket socket = new DatagramSocket();


socket.send(packet);

AP : Network Prog. 70
DatagramReceiver

0 The steps are the reserve of sending:


0 Create an empty DatagramPacket (and allocate a buffer
for the incoming data)
0 Create a DatagramSocket on an agreed socket number to
provide access to arrivals
0 Use the socket to receive the datagram (the thread will
block until a new datagram arrrives)
0 Extract the data bytes which make up the message

AP : Network Prog. 71
DatagramReceiver
// Create an empty packet with some buffer space
byte[] data = new byte[1500];
DatagramPacket packet =
new DatagramPacket(data, data.length);

DatagramSocket socket = new DatagramSocket(9876);

// This call will block until a datagram arrives


socket.receive(packet);

// Convert the bytes back into a String and print


String message =
new String(packet.getData(), 0, packet.getLength());
System.out.println("message is " + message);
System.out.println("from " + packet.getAddress());
AP : Network Prog. 72
But it’s never quite that simple!
0 Several of the constructors/methods throw
exceptions which we have omitted
0 Each datagrams can only hold up to a maximum of
64KB of data . .
0 . . but the underlying transport layer may split the
message into smaller packets (for instance Ethernet
uses about 1500 bytes)
0 Always remember that UDP is an unreliable protocol:
If any of the split datagrams are lost the whole
message will be lost

AP : Network Prog. 73
Example: Java server (UDP)
import java.io.*;
import java.net.*;

class UDPServer {
public static void main(String args[]) throws Exception
Create {
datagram socket
DatagramSocket serverSocket = new DatagramSocket(9876);
at port 9876
byte[] receiveData = new byte[1024];
byte[] sendData = new byte[1024];

while(true)
{
Create space for
DatagramPacket receivePacket =
received datagram
new DatagramPacket(receiveData, receiveData.length);
Receive serverSocket.receive(receivePacket);
datagram

AP : Network Prog. 74
Example: Java server (UDP), cont
String sentence = new String(receivePacket.getData());
Get IP addr
port #, of InetAddress IPAddress = receivePacket.getAddress();
sender
int port = receivePacket.getPort();

String capitalizedSentence = sentence.toUpperCase();

sendData = capitalizedSentence.getBytes();
Create datagram
to send to client DatagramPacket sendPacket =
new DatagramPacket(sendData, sendData.length, IPAddress, port);
Write out
datagram serverSocket.send(sendPacket);
}
to socket
}
}
End of while loop,
loop back and wait for
another client connection 75

AP : Network Prog.
Example: Java client (UDP)
import java.io.*;
import java.net.*;

class UDPClient {
public static void main(String args[]) throws Exception
{
Create
input stream BufferedReader inFromUser =
new BufferedReader(new InputStreamReader(System.in));
Create
client socket DatagramSocket clientSocket = new DatagramSocket();
Translate
InetAddress IPAddress = InetAddress.getByName("hostname");
hostname to IP
address using DNS byte[] sendData = new byte[1024];
byte[] receiveData = new byte[1024];

String sentence = inFromUser.readLine();


sendData = sentence.getBytes(); 76

AP : Network Prog.
Example: Java client (UDP), cont.
Create datagram with
data-to-send, DatagramPacket sendPacket =
length, IP addr, port new DatagramPacket(sendData, sendData.length, IPAddress, 9876);

Send datagram clientSocket.send(sendPacket);


to server
DatagramPacket receivePacket =
new DatagramPacket(receiveData, receiveData.length);
Read datagram
clientSocket.receive(receivePacket);
from server
String modifiedSentence =
new String(receivePacket.getData());

System.out.println("FROM SERVER:" + modifiedSentence);


clientSocket.close();
}
}
AP : Network Prog. 77
IP addresses revisited
0 Each 32 bit IP number consists of two components:
0 The network address
0 The unique international address of the network
0 The host address
0 The unique address of a specific host in the net
0 There are three classes of network address denoted
class ‘A’, ‘B’ and ‘C’

AP : Network Prog. 78
0
Broadcasting
A broadcast address is a logical address at which all devices connected to a
multiple-access communications network are enabled to receive datagrams. A
message sent to a broadcast address is typically received by all network-
attached hosts, rather than by a specific host.
0 Broadcasting allows a single datagram to be sent to a group of listeners
0 The group consists of all the computers within the local network
0 The previous code examples can be used for broadcasting
0 Just change the address: each network has a unique broadcast address
0 he broadcast address for an IPv4 host can be obtained by performing a
bitwise OR operation between the bit complement of the subnet mask and the
host's IP address.
0 Example: For broadcasting a packet to an entire IPv4 subnet using the private
IP address space 172.16.0.0/12, which has the subnet mask 255.240.0.0, the
broadcast address is 172.16.0.0 | 0.15.255.255 = 172.31.255.255.
0 A special definition exists for the IP broadcast address 255.255.255.255. It is
the broadcast address of the zero network or 0.0.0.0, which in Internet
Protocol standards stands for this network, i.e. the local network.
Transmission to this address is limited by definition, in that it is never
forwarded by the routers connecting the local network to other networks.
0 IP broadcasts are used by BOOTP and DHCP clients to find and send requests
to their respective servers.
AP : Network Prog. 79
Broadcast addresses
0 CIIPS has a class ‘C’ network which has the address
130.95.72
0 This portable computer has host address 134 within
the CIIPS network
0 Each network has a single host address which is set
aside for broadcasts (either all one bits or all zero
bits)
0 The CIIPS network uses broadcast address
130.95.72.255
0 Broadcasts are never routed onto other networks

AP : Network Prog. 80
Multicasting
0 A multicast address is a logical identifier for a group of hosts
in a computer network, that are available to process
datagrams or frames intended to be multicast for a designated
network service. Multicast addressing can be used in the Link
Layer (Layer 2 in the OSI model), such as Ethernet multicast,
and at the Internet Layer (Layer 3 for OSI) for Internet
Protocol Version 4 (IPv4) or Version 6 (IPv6) multicast.
0 Multicasting allows distribution of a datagram to a group of
listeners who are not within the local network
0 Routers between networks need to pass multicast datagrams. .
but many do not!
0 The MBONE is a way of tunneling datagrams across the
Internet between islands of multicast activity
AP : Network Prog. 81
Multicasting
0 IPv4 multicast addresses are defined by the leading address bits
of 1110, originating from the classful network design of the
early Internet when this group of addresses was designated as
Class D. The Classless Inter-Domain Routing (CIDR) prefix of this
group is 224.0.0.0/4. The group includes the addresses from
224.0.0.0 to 239.255.255.255.
0 Multicasts are also sent to a special address (known as a
“group”)
0 Multicast groups need to be agreed in advance. They are not
derived from a specific network/host address
0 Multicast groups identify a subject area (or stream of content)
rather than a specific computer or network. They are more like a
TV channel number than a telephone number.
0 The IETF has set aside addresses from 224.0.0.1 to
239.255.255.255 specifically for multicasting
AP : Network Prog. 82
Multicasting
0 To send to (or receive from) a multicast group it is first
necessary to register interest in the group
0 This results in an Internet Group Management Protocol (IGMP)
message being sent to your router (RFCs 988/1112/2236)
0 Then a datagram is created, addressed to the group (and the
chosen port)
0 Java has a specialised socket for multicasting:
java.net.MulticastSocket

AP : Network Prog. 83
Some multicast groups
0 224.0.0.1 All hosts within local subnet
0 224.0.1.7 Audio news multicast
0 224.0.1.12 Video from IETF meetings
0 224.0.1.20 Expts. within local subnet
0 224.0.1.25 NBC Professional News
0 There are 268 million multicast addresses (in IPv4)
with 65 thousand ports in each!

AP : Network Prog. 84
java.net.MulticastSocket
0 Subclass of java.net.DatagramSocket
0 Constructed the same way
0 Adds some extra methods:
0 void joinGroup(InetAddress mcastGroup)
0 Enter the specifies group so that you can send or receive datagrams
0 void leaveGroup(InetAddress mcastGroup)
0 Leave a group that you previously joined
0 void setTimeToLive(int ttl)
0 Sets how far your datagrams will travel before routers ignore them
0 int getTimeToLive()

AP : Network Prog. 85
MulticastSender
0 Sending similar to the previous example. .
0 . . .but must register with the multicast group and decide
the longevity
0 The steps involved are:
0 Create the MulticastSocket.
0 Join the multicast group(s) (on startup).
0 Create the DatagramPacket.
0 Send the packet through the socket.
0 Leave the multicast group (on exit).

AP : Network Prog. 86
MulticastSender
InetAddress multicastGroup =
InetAddress.getByName(multicastGroupAddr);
MulticastSocket socket = new MulticastSocket();
socket.joinGroup(multicastGroup);
socket.setTimeToLive(5);

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


DatagramPacket datagram =
new DatagramPacket(data, data.length);
datagram.setAddress(multicastGroup);
datagram.setPort(9876);

socket.send(datagram);

socket.leaveGroup(multicastGroup);

AP : Network Prog. 87
MulticastReceiver
0 The steps are:
0 Create a multicast socket on an agreed port.
0 Join the multicast group (on startup).
0 Create an empty datagram.
0 Wait for datagram to be delivered on the socket.
0 Unpack and use the datagram.
0 Leave the multicast group (on exit).

AP : Network Prog. 88
MulticastReceiver
InetAddress multicastGroup =
InetAddress.getByName(multicastGroupAddr);
MulticastSocket socket = new MulticastSocket(9876);
socket.joinGroup(multicastGroup);

byte[] data = new byte[1000];


DatagramPacket packet =
new DatagramPacket(data, data.length);
socket.receive(packet);

String message = new String(


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

socket.leaveGroup(multicastGroup);

AP : Network Prog. 89
Notice
0 I’ve send all the demonstrations to your email.

AP - Chapter 5 (Thread) 90

You might also like