Chapter 7 Network Programming
Chapter 7 Network Programming
Chapter 7 Network Programming
Prog.
Network
Programmin
k
Networ
AP :
g
1
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
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
0 Programming Interface:
Network
0 Sockets (IP,..)
0 Network Layer Link
0 IP (device driver,..)
0 Link Layer
0 Device drivers
AP : Network Prog. 4
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. 5
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. 6
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.
TCP or UDP
Packet
AP : Network Prog. 7
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. 8
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. 9
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. 10
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. 11
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. 12
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. 13
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
0 Master / worker
Server
0 Peer-to-peer (P2P)
Client
AP : Network Prog. 14
Elements of Client -Server
Computing
a client, a server, and network
e st
qu
Re
Client
Server
Network
Re
su
lt
Client machine
Server machine
AP : Network Prog. 15
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. 16
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. 17
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. 18
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. 19
TCP - Connection Oriented
0 TCP Protocol
AP : Network Prog. 20
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. 21
java.net.ServerSocket (1)
AP : Network Prog. 22
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. 23
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. 24
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. 25
Implementing
1. Open the Server Socket:
a Server
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. 26
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. 27
Example: Java server (TCP)
import java.io.*;
import java.net.*;
class TCPServer {
AP : Network Prog. 29
Example: Java client (TCP)
import java.io.*;
import java.net.*;
class TCPClient {
30
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');
clientSocket.close();
}
}
AP : Network Prog. 31
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. 32
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. 33
Client/server socket interaction: TCP
Server (running on hostid) Client
create socket,
port=x, for
incoming request:
welcomeSocket =
ServerSocket()
write reply to
connectionSocket read reply from
clientSocket
close
connectionSocket close
AP : Network Prog. clientSocket 34
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) .
0 Most networks cannot guarantee reliable delivery of
datagrams
AP : Network Prog. 35
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. 36
End of Chap
Networ
k Prog. te r
AP :
37