2. Elements of Client -Server Computing
5/26/2023
Network
client, server, and network
Client
Server
Client machine
Server machine
3. Overview
5/26/2023
The term Network programming refers to writing programs that execute
across multiple devices (computers) in which the devices are all connected to
each other using a network.
4. Networking
• Java’s fundamental networking capabilities are declared by classes
and interfaces of the java.net package, through which Java
offers stream-based communications.
• The classes and interfaces of java.net also offer packet-based
communications for transmitting individual packets of information.
This is most commonly used to transmit audio and video over the
Internet.
• We will focus on both sides of the client-server relationship.
• The client requests that some action be performed, and the server
performs the action and responds to the client.
5/26/2023
5. Networking Classes in the JDK
• Through the classes in java.net Java programs can use TCP or UDP to
communicate over the Internet.
• For TCP communication:
Socket
ServerSocket
• For UDP communication:
DatagramPacket
DatagramSocket
MulticastSocket
5/26/2023
6. TCP
• TCP (Transmission Control Protocol)
• A connection-oriented protocol.
• Allows reliable communication between two applications.
• Usually used over the Internet with IP as TCP/IP
• Resembles making a telephone call
• The person placing the telephone call – client
• The person waiting for a call – server
• The java.net.ServerSocket and java.net.Socket classes are the only two
classes you will probably ever need to create a TCP/IP connection between
two computers.
• For a secure connection, SSLServerSocket and SSLSocket classes in the
javax.net.ssl package are used.
5/26/2023
7. .. TCP
• Guarantees that data sent from one end of the connection actually gets
to the other end and in the same order it was sent. Otherwise, an error
is reported.
• The Hypertext Transfer Protocol (HTTP), File Transfer Protocol (FTP), and
Telnet are all examples of applications that require a reliable
communication channel.
5/26/2023
8. UDP
• UDP (User Datagram Protocol)
• A connectionless protocol.
• Allows packets of data (datagram) to be transmitted between applications.
• Resembles mailing someone a letter
• The datagram packet is like a letter, where a client sends a datagram to a server without
actually connecting to the server.
• This makes UDP an unreliable protocol
• UDP does not guarantee that packets will be received in the order they were sent
or that they will even be delivered at all.
• The java.net.DatagramPacket class –to send datagram packets
• The java.net.DatagramSocket class – to receive datagram packets
5/26/2023
9. …UDP
–Sender does not wait for acknowledgements
–Arrival order is not guaranteed
–Arrival is not guaranteed
• USED when speed is essential, even in cost of reliability
–e.g. streaming media, games, Internet telephony, etc.
5/26/2023
10. IP Address and Ports
• Data transmitted over the Internet is accompanied by addressing
information that identifies the computer and the port for which it
is destined.
– The computer is identified by its 32-bit IP address, which IP uses to
deliver data to the right computer on the network.
– Ports are identified by a 16-bit number, which TCP and UDP use to
deliver the data to the right application.
10
11. …Ports
• Port numbers range from 0 to 65,535 (16-bit)
• Ports 0 - 1024 are called well-known ports. They are
reserved for use by well-known services:
• 20, 21: FTP
• 23: TELNET
• 25: SMTP
• 110: POP3
• 80: HTTP
11
12. 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.net.InetAddress : Represents an IP address
(either IPv4 or IPv6) and has methods for performing DNS lookup.
• InetAddress getByName(String host) throws UnknownHostException
• InetAddress[] getAllByName(String host)throws UnknownHostException
• InetAddress getLocalHost() throws UnknownHostException
• boolean isMulticastAddress()
• String getHostName()
• byte[] getAddress()
• String getHostAddress()
• int hashCode()
• boolean equals(Object obj)
• String toString()
2/4/2013 Ch4: Network Programming Compiled by:Kidane W. 12
13. Sockets
• A program can read from a socket or write to a socket as simply as
reading from a file or writing to a file.
• A socket is simply a software construct that represents one
endpoint of a connection.
• Stream sockets enable a process to establish a connection with
another process. While the connection is in place, data flows
between the processes in continuous streams.
• Stream sockets provide a connection-oriented service. The
protocol used for transmission is the popular TCP (Transmission
Control Protocol). Provides reliable , in-order byte-stream service
5/26/2023
14. Sockets and Java Socket Classes
• A socket is an endpoint of a two-way communication link between two
programs running on the network.
• A socket is bound to a port number so that the TCP layer can identify
the application that data destined to be sent.
• Java’s .net package provides two classes:
• Socket – for implementing a client
• ServerSocket – for implementing a server
5/26/2023
15. Socket Communication
• A server (program) runs on a specific computer and has a socket that
is bound to a specific port.
• The server waits and listens to the socket for a client to make a
connection request.
5/26/2023
server
Client
Connection request
port
16. Socket Communication
• If everything goes well, the server accepts the connection.
• Upon acceptance, the server gets a new socket bounds to a different port. It
needs a new socket (consequently a different port number) so that it can
continue to listen to the original socket for connection requests while serving the
connected client.
5/26/2023
server
Client
Connection
port
port
port
18. Socket
• There are four fundamental operations a socket performs. These are:
Connect to a remote machine
Send data
Receive data
Close the connection
• The java.net.Socket class allows you to perform all four
fundamental socket operations
• Connection is accomplished through the constructors.
• Each Socket object is associated with exactly one remote host. To
connect to a different host, you must create a new Socket object.
5/26/2023
19. Socket constructors
Socket(String host, int port) throws UnknownHostException, IOException
Socket(InetAddress address, int port) throws IOException
Socket(String host, int port, InetAddress localAddress, int localPort) throws
IOException
Socket(InetAddress address, int port, InetAddress localAddress, int localPort)
throws IOException
• Sending and receiving data is accomplished with output and input
streams.
InputStream getInputStream() throws IOException
OutputStream getOutputStream() throws IOException
• There's a method to close a socket.
void close() throws IOException
5/26/2023
20. Socket methods
• There are methods to return information about the socket:
InetAddress getInetAddress()
InetAddress getLocalAddress()
int getPort()
int getLocalPort()
• Finally there's the usual toString() method:
String toString()
5/26/2023
21. Constructing Socket Objects
• You need to at least specify the remote host and port you want to connect to.
Socket webSunsite = new Socket("metalab.unc.edu", 80);
Socket metalab = new Socket("metalab.unc.edu", 80, "calzone.oit.unc.edu",
0);
• The later constructors also specify the host and port you're connecting from.
• On a system with multiple IP addresses, like many web servers, this allows you to pick your network
interface and IP address.
• you should probably set the port number to 0 instead to tells the system to randomly choose an
available port.
• The Socket() constructors create a Socket object & attempt to connect the underlying socket to
the remote server.
5/26/2023
22. Socket Programming with TCP
• Server process must first be running (must have created
a socket). Recall that TCP is not connectionless.
• Client contacts the server by creating client-local socket
specifying IP address and port number of server process.
Client TCP establishes connection to server TCP.
• When contacted by client, server TCP creates a new
socket for server process to communicate with client.
• Allows server to talk with multiple clients
• Source port numbers used to distinguish clients
• From application viewpoint: TCP provides reliable, in-
order transfer of bytes (“pipe”) between client and
server.
5/26/2023
23. Establishing a Simple Server Using Stream Sockets
Five steps to create a simple stream server in Java:
1. ServerSocket object. Registers an available port and a
maximum number of clients.
2. Each client connection handled with a Socket object. Server
blocks until client connects.
3. Sending and receiving data
• OutputStream to send and InputStream to receive
data.
• Methods getInputStream and getOutputStream on
Socket object.
4. Process phase. Server and client communicate via streams.
5. Close streams and connections.
5/26/2023
24. Establishing a Simple Client Using Stream Sockets
Four steps to create a simple stream client in Java:
1. Create a Socket object for the client.
2. Obtains Socket’s InputStream and OutputStream.
3. Process information communicated.
4. Close streams and Socket.
5/26/2023
25. Sockets
int port=2000;
BufferedReader br;
PrintWriter pw;
ServerSocket ss;
Socket sock;
ss = new ServerSocket(port);
sock = ss.accept();
br = new BufferedReader(
new InputStreamReader(
(sock.getInputStream());
pw = new PrintWriter(
sock.getOutputStream());
System.out.println(
br.readLine());
pw.println("HELLO");
int port=2000;
String host=”cubist";
BufferedReader br;
PrintWriter pw;
Socket sock;
sock = new Socket(host,port);
br = new BufferedReader(
new InputStreamReader(
(sock.getInputStream());
pw = new PrintWriter(
sock.getOutputStream());
pw.println("ciao");
System.out.println(
br.readLine());
Server Client
26. Example: Java server using TCP
5/26/2023
//simple server application using TCP
import java.io.*;
import java.net.*;
class TCPServer {
public static void main (String args[]) throws Exception
{
String clientSentence;
String capitalizedSentence;
//create welcoming socket at port 6789
ServerSocket welcomeSocket = new ServerSocket(6789);
while (true) {
//block on welcoming socket for contact by a client
Socket connectionSocket = welcomeSocket.accept();
//create input stream attached to socket
BufferedReader inFromClient = new BufferedReader(new
InputStreamReader
(connectionSocket.getInputStream()));
27. Example: Java server using TCP (cont.)
5/26/2023
//create output stream attached to socket
DataOutputStream outToClient = new
DataOutputStream(connectionSocket.getOutputStream());
//read in line from the socket
clientSentence = inFromClient.readLine();
//process
capitalizedSentence = clientSentence.toUpperCase() + 'n';
//write out line to socket
outToClient.writeBytes(capitalizedSentence);
}
}
}
28. Example: Java client using TCP
5/26/2023
//simple client application using TCP
import java.io.*;
import java.net.*;
class TCPClient {
public static void main (String args[]) throws Exception
{
String sentence;
String modifiedSentence;
//create input stream
BufferedReader inFromUser = new BufferedReader(new
InputStreamReader(System.in));
//create client socket and connect to server
Socket clientSocket = new Socket("localhost", 6789);
//create output stream attached to socket
DataOutputStream outToServer = new
DataOutputStream(clientSocket.getOutputStream());
29. Example: Java client using TCP (cont.)
5/26/2023
//create input stream attached to socket
BufferedReader inFromServer = new BufferedReader(new
InputStreamReader (clientSocket.getInputStream()));
sentence = inFromUser.readLine();
//send line to server
outToServer.writeBytes(sentence + 'n');
//read line from server
modifiedSentence = inFromServer.readLine();
System.out.println("FROM SERVER: " + modifiedSentence);
clientSocket.close();
}
}
30. Start TCP Server
executing
Start a TCP Client
executing and send
message to server.
Server responds and client
process terminates. The
server is still executing.
Another client begins
execution and the cycle
repeats.
5/26/2023
31. Socket programming with UDP
• Datagram sockets transmit individual packets of information. This is
typically not appropriate for use by everyday programmers because the
transmission protocol is UDP (User Datagram Protocol).
• UDP provides a connectionless service. A connectionless service does
not guarantee that packets arrive at the destination in any particular
order.
• With UDP, packets can be lost or duplicated. Significant extra
programming is required on the programmer’s part to deal with these
problems.
• UDP is most appropriate for network applications that do not require
the error checking and reliability of TCP.
5/26/2023
32. …UDP
• Under UDP there is no “connection” between the server and the client.
There is no “handshaking”.
• The sender explicitly attaches the IP address and port of the destination
to each packet.
• The server must extract the IP address and port of the sender from the
received packet.
• From an application viewpoint, UDP provides unreliable transfer of groups
of bytes (“datagrams”) between client and server.
5/26/2023
33. …UDP
1. Create an array of bytes large enough to hold the data of the incoming
packet.
2. A DatagramPacket object is instantiated using the array of bytes.
3. A DatagramSocket is instantiated, and it is specified which port (and
specific localhost address, if necessary) on the localhost the socket will
bind to.
4. The receive() method of the DatagramSocket class is invoked, passing in
the DatagramPacket object. This causes the thread to block until a
datagram packet is received or a time out occurs.
5/26/2023
Steps to Receive a Datagram packet - UDP
34. …UDP
1. Create an array of bytes large enough to hold the data of the packet to be
sent, and fill the array with the data.
2. Create a new DatagramPacket object that contains the array of bytes, as well
as the server name and port number of the recipient.
3. A DatagramSocket is instantiated, and it is specified which port (and specific
localhost address, if necessary) on the localhost the socket will bind to.
4. The send() method of the DatagramSocket class is invoked, passing in the
DatagramPacket object.
5/26/2023
Steps to Send a Datagram packet - UDP
35. Example: Java server using UDP
5/26/2023
import java.io.*;
import java.net.*;
class UDPServer {
public static void main(String args[]) throws Exception
{
//Create datagram socket on port 9876
DatagramSocket serverSocket = new DatagramSocket(9876);
byte[] sendData = new byte[1024];
byte[] receiveData = new byte[1024];
while (true)
{
//create space for the received datagram
DatagramPacket receivePacket = new
DatagramPacket(receiveData,
receiveData.length);
//receive the datagram
serverSocket.receive(receivePacket);
String sentence = new String(receivePacket.getData());
36. …Example: Java server using UDP
5/26/2023
//get IP address and port number of sender
InetAddress IPAddress = receivePacket.getAddress();
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 the datagram to the socket
serverSocket.send(sendPacket);
} //end while loop
}
}
37. Example: Java client using UDP
5/26/2023
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 hostname to IP address using DNS
InetAddress IPAddress = InetAddress.getByName("localhost");
byte[] sendData = new byte[1024];
byte[] receiveData = new byte[1024];
String sentence = inFromUser.readLine();
sendData = sentence.getBytes();
38. …Example: Java client using UDP
5/26/2023
DatagramPacket sendPacket = new DatagramPacket(sendData,
sendData.length, IPAddress, 9876);
clientSocket.send(sendPacket);
DatagramPacket receivePacket = new DatagramPacket(receiveData,
receiveData.length);
clientSocket.receive(receivePacket);
String modifiedSentence = new String(receivePacket.getData());
System.out.println("FROM SERVER: " + modifiedSentence);
clientSocket.close();
}
}
39. Start UDP server
executing
Start UDP client
executing
Client sends a
message
(datagram) to the
server
Server responds by
returning the
datagram to the
client in all capital
letters
5/26/2023