Title: Socket Programming TCPUDP in Java
1Socket Programming (TCP/UDP) in Java
2Introduction
- The Client-Server paradigm is the most prevalent
model for distributed computing protocols. - It is the basis of all distributed computing
paradigms at a higher level of abstraction. - It is service-oriented, and employs a
request-response protocol.
3The Client-Server Paradigm
- A server process, running on a server host,
provides access to a service. - A client process, running on a client host,
accesses the service via the server process. - The interaction of the process proceeds according
to a protocol.
4The Client-Server Paradigm
5Client-Server System Architecture vs
Client-Server Distributed computing
- In the client-server system architecture, the
terms clients and servers refer to computers,
while in the client-server distributed computing
paradigm, the terms refer to processes.
6Client-server, an overloaded term
7A Protocol / Service Session
- In the context of the client-server model, we
will use the term session to refer to the
interaction between the server and one client. - The service managed by a server may be accessed
by multiple clients who desire the service,
sometimes concurrently. - Each client, when serviced by the server, engages
in a separate session with the server, during
which it conducts a dialog with the server until
the client has obtained the service it required
8A Service Session
9The Protocol for a Network Service
- A protocol is needed to specify the rules that
must be observed by the client and the server
during the conduction of a service. - Such rules include specifications on matters such
as - how the service is to be located
- the sequence of interprocess communication, and
- the representation and interpretation of data
exchanged with each IPC.
10Locating a Service
- A mechanism must be available to allow a client
process to locate a server for a given service. - A service can be located through the address of
the server process, in terms of the host name and
protocol port number assigned to the server
process. This is the scheme for Internet
services. - Each Internet service is assigned to a specific
port number. - In particular, a well-known service such as ftp,
HTTP, or telnet is assigned a default port number
reserved on each Internet host for that service.
11Implementing a Network Service
- Any implementation of the client or server
program for this service is expected to adhere to
the specification for the protocol, including how
the dialogs of each session should proceed. - Among other things, the specification defines
- which side (client or server) should speak first,
- the syntax and semantic of each request and
response, and - the action expected of each side upon receiving a
particular request or response. - Typically, the interaction of the client and
server processes follows a request-response
pattern.
12IPC between Client and Server
13Session IPC Examples
- Daytime service RFC867
- Client Hello, ltclient addressgt here. May I have
a timestamp please. - Server Here it is (time stamp follows)
- World Wide Web session
- Client Hello, ltclient addressgt here.
- Server Okay. I am a web server and speaks
protocol HTTP1.0. - Client Great, please get me the web page
index.html at the root of your document tree. - Server Okay, heres whats in the page
(contents follows).
14Client-Server Protocol Data Representation
- Part of the specification of a protocol is the
syntax and semantics of each request and
response. - The choice of data representation depends on the
nature and the needs of the protocol. - Representing data using text (character strings)
is common, as it facilitates data marshalling and
allows the data to be readable by human. - In Java, there are also cases that the data
values are directly passed between the client and
server - Most well known Internet protocols are
client-server, request-response, and text-base.
15Structure of Network Application
- Client-side networking
- You are given a specific server and you are
concerned with how to communicate with the server - For example, you may write a network program to
connect to a Web server - Server-side networking
- You are creating a server that accepts connection
requests from clients - For example, you may write a network program to
provide network services to the world - Usually, we will do both client-side and
server-side networking when we are developing a
new network application
16Flow of Server-Side Application
- Listen for client requests on a particular port
- When a communication request arrives, create the
connection - Create the I/O streams for the communication.
Communicate with the client using the client
connection - Close the streams and the client connection when
the communication is completed.
17Flow of Client-Side Application
- Identify the target server and the service
- IP address and port number
- Create a connection to the target server and
service - Wait for the server to respond to the connection
request - Create the I/O streams for the communication.
Read and write to the connection and perform the
application logic - Close the streams and connection when the
communication is completed
18Connectionless vs. Connection-Oriented Servers
- A connectionless server
- Uses a connectionless IPC API (e.g.,
connectionless datagram socket) - Sessions with concurrent clients can be
interleaved. - A connection-oriented server
- Uses a connection-oriented IPC API (e.g.
stream-mode socket ) - Sessions with concurrent clients can only be
sequential unless the server is threaded
19Concurrent vs. Iterative Servers
- A connection-oriented server can be threaded so
that it can service multiple clients
concurrently. Such a server is said to be a
concurrent server. - An unthreaded connection-oriented server is said
to be an iterative server.
20A Concurrent, Connection-Oriented Server
21Sequence Diagram for a Concurrent Server
22Echo Server Concurrent Sessions
23Session State Information
- For some protocols or applications, a server must
maintain information specific to a client during
its service session. - Consider a network service such as file transfer.
- A file is typically transferred in blocks,
requiring several rounds of data exchanges to
complete the file transfer. - The dialog during a session proceeds roughly as
follows - Client Please send me the file foo in directory
someDir. - Server Okay. Here is block 1of the file
- Client Got it.
- Server. Okay. Here is block2 of the file
- Client Got it.
24Stateful vs. Stateless Servers
- A stateful server maintain session state
information on each active client. - Stateless server is straightforward to code.
- Stateful server is harder to code, but the state
information maintained by the server can reduce
the data exchanged, and allows enhancements to a
basic service. - Maintaining stateful information is difficult in
the presence of failures. - In actual implementation, a server may be
stateful, stateless or hybrid wherein the state
data is distributed on both the server-side and
the client-side
25Stateless and Stateful Servers
26Failure in Stateful Server
27InetAddress Class
- java.net.InetAddress is used to deal with IP
addresses - 3 static methods can be used to resolve the IP
address of a host - InetAddress.getByName(String hostname)
- for first IP (as an InetAddress object)
- InetAddress.getAllByName(String hostname)
- for multiple IP (as an InetAddress
array)Multiple IPs are used to distribute
workload for a service among the server machines - InetAddress.getLocalHost( )
- for localhost (as an InetAddress object)
28Simple TCP Connection in Java Stream Server
Socket
- In Java, TCP connection is made using Stream
Socket - ServerSocket class create a server bound to a
specific port - Constructor ServerSocket(int port), throw
IOException - accept() method listens for a connection request
and accepts it, the return value is the accepted
client socket - close() method closes the server socket
29Simple TCP Connection in Java Stream Socket
- Socket class create a steam socket and connects
it to a specific port at a specific IP address
(server) - Constructor Socket(String host, int port), throw
IOException - getInputStream() returns an input stream from the
other side of the socket. May generate
IOException. - getOutputStream() returns an output stream to the
other side of the socket. May generate
IOException. - close() closes the socket
30Steps in Establishing Stream Sockets in Java
- Network connection establishment requires to
import java.net. - The server specifies that it is waiting for
connection at a particular port - A client attempts to connect to the server at the
port on the host (server) - If attempts succeeded, two sockets are created
- Communication can be done through the data
input/output streams (java.io. needed)
31Stream Sockets on Server Side
- Server specifies that it is waiting for
connection using ServerSocket class - Example ServerSocket server ServerSocket(5000)
- if port number cannot be used, IOException is
thrown - Server declares its intention of accepting client
connection by the method accept - Socket client server.accept( )
- When a client is successfully connected, the
method returns a Socket of client - getInputStream and getOutputStream methods of
Socket establish the communication channels with
the client - DataInputStream in client.getInputStream()
- DataOutputStream out client.getOutputStream()
32Stream Sockets on Client Side
- Two Socket constructor can be used to connect a
server - Socket(String hostname, int portNo)
- Socket(InetAddress inetAdd, int portNo)
- local available port is allocated arbitrarily,
can be retrieved through getLocalPort method of
Socket - remote port (at server) can be obtained by
getPort method of Socket - As in the server side, getInputStream and
getOutputSteram are used to establish
communication channels
33Sample Program on Client/Server
- Echo Server
- Server declares listening at a specific port
- Server blocks at accept statement till connection
is established - Server read Strings from the client and write it
back to the client through the I/O streams until
the "CLOSE" message is read
- Echo Client
- Client try to connect to the server host at the
specific port - Socket created if server is successfully
connected - Writer object is used to output the message from
the keyboard (read from a BufferedReader object)
to the server - Another BufferedReader object is used to read the
bounce-back message from the server
34TCP EchoServer Sample Code
- import java.io.
- import java.net.
- public class TCPEchoServer
- private static ServerSocket servSock
- private static final int PORT 22222
- public static void main(String args)
- System.out.println("Opening port...\n")
- try
- servSock new ServerSocket(PORT)
//Step 1. - catch(IOException e)
- System.out.println("Unable to attach to
port!") - System.exit(1)
-
- do
- run()
- while (true)
-
35- private static void run()
- Socket link null //Step 2.
- try
- link servSock.accept() //Step 2.
- BufferedReader in new BufferedReader( //Step
3. new InputStreamReader(link.getInputStream())
) - PrintWriter out new PrintWriter( link.get
OutputStream(),true) //Step 3. - int numMessages 0
- String message in.readLine() //Step 4.
- while (!message.equals("CLOSE"))
- System.out.println("Message received.")
- numMessages
- out.println("Message " numMessages "
" message) //Step 4. - message in.readLine()
-
- out.println(numMessages " messages
received.") //Step 4. - catch(IOException e) e.printStackTrace()
- finally
- try
- System.out.println("\n Closing connection...
")
36TCP EchoClient Sample Code
- import java.io.
- import java.net.
- public class TCPEchoClient
- private static String host
- private static final int PORT 22222
- public static void main(String args)
- if(args.length 1) host args0
- else
- System.out.println( "Usage java
TCPEchoClient lthostnamegt") - System.exit(1)
-
- run()
-
37TCP EchoClient Sample Code (cont'd)
- private static void run()
- Socket link null //Step 1.
- try
- link new Socket(host,PORT) //Step 1.
- BufferedReader in new BufferedReader( //Step
2. new InputStreamReader(link.getInputStream()
)) - PrintWriter out new PrintWriter( link.getO
utputStream(),true) //Step 2. - //Set up stream for keyboard entry...
- BufferedReader userEntry new
BufferedReader( new InputStreamReader(System.in
)) - String message, response
- do
- System.out.print("Enter message ")
- message userEntry.readLine()
- out.println(message) //Step 3.
- response in.readLine() //Step 3.
- System.out.println("\nSERVERgt " response)
- while (!message.equals("CLOSE"))
38TCP EchoClient Sample Code (cont'd)
- catch(IOException e)
- e.printStackTrace()
- finally
- try
- System.out.println( "\n Closing
connection... ") - link.close() //Step 4.
- catch(IOException e)
- System.out.println("Unable to disconnect!")
- System.exit(1)
-
-
-
39Multithreaded Server
- In our previous example, the echo server handles
one connection at one time - It is okay when the interaction with client
completes in a short time - It will block other connections and cause
time-out if the connection needs to maintain for
a long time - Useful server has to be multithreaded in order to
handle multiple and simultaneous connections - Modified server will create a dedicated thread
for each client every time it accept a connection - All server operations are done in the thread
instead of main program includes creating
independent IO streams to each client - Each thread reads the respective data from each
client and writes to the screen
40Client-Server Chat Application Server
- Basic requirement of a chat server
- It has to be multithreaded multiple clients
will be served simultaneously - It has to keep track of all chat participants
- When it receives a message from any participant,
it has to broadcast the message to all other
participants - Flow of the server
- Create a server socket to accept incoming
connections - When a connection arrives, create a new thread to
handle the connection. The handlers has to be
stored in a place that all threads can access
(for broadcasting) - In the handler thread, wait for incoming
messages. Broadcast the message to all other
handlers when an incoming message is received
41Chat Server Sample Code
- import java.net.
- import java.io.
- public class ChatServer
- public static void main(String args) throws
IOException - if (args.length ! 1)
- throw new IllegalArgumentException( "Syntax
ChatServer ltportgt") - int port Integer.parseInt(args0)
- ServerSocket server new ServerSocket(port)
- // listen for connections
- while (true)
- Socket client server.accept()
- System.out.println("New client from "
client.getInetAddress()) - // spawn new handler
- ChatHandler handler new ChatHandler(client)
- handler.start()
-
-
42Chat Handler in Server
- Each handler thread interact with one client
- A static vector stores all running chat handlers
- Handler is added to the vector when start()
method is called - Handler is removed from the vector when stop() is
called - Message is broadcasted to all handlers in the
vector - We use DataInputStream and DataOutputStream to
read/write the message - readUTF() / writeUTF() enables us to read/write
multi-lingual text - Any method that needs to access the static
variable needs to be synchronized
43Chat Handler Sample Code
- import java.io.
- import java.net.
- import java.util.
- public class ChatHandler implements Runnable
- // the vector of all handlers
- protected static Vector handlers new Vector()
- protected Socket socket
- protected DataInputStream dataIn
- protected DataOutputStream dataOut
- protected Thread listener
- public ChatHandler(Socket socket)
- this.socket socket
-
44- public synchronized void start()
- if (listener null)
- try
- dataIn new DataInputStream( new
BufferedInputStream( socket.getInputStream()))
- dataOut new DataOutputStream( new
BufferedOutputStream( socket.getOutputStream()
)) - listener new Thread(this)
- listener.start()
- catch (IOException ignored)
-
-
- public synchronized void stop()
- if (listener ! null)
- try
- if (listener ! Thread.currentThread())
- listener.interrupt()
- listener null
- dataOut.close()
- catch (IOException ignored)
45- public void run()
- try
- // add us to the pool of handlers
- handlers.addElement(this)
- while (!Thread.interrupted())
- // read a message and broadcast it
- String message dataIn.readUTF()
- broadcast(message)
-
- catch (EOFException ignored)
- catch (IOException ex)
- if (listener Thread.currentThread())
- ex.printStackTrace()
- finally
- // thread is to exit, so remove us from
handler - handlers.removeElement(this)
-
- stop()
-
46- protected void broadcast(String message)
- synchronized (handlers)
- Enumeration enum handlers.elements()
- while (enum.hasMoreElements())
- ChatHandler handler (ChatHandler)
enum.nextElement() - try
- handler.dataOut.writeUTF(message)
- handler.dataOut.flush()
- catch (IOException ex)
- // the connection may have dropped
- handler.stop()
-
-
-
-
47Client-Server Chat Application Client
- The client contains a simple user interface with
an output area and an input box - When user hits ltReturngt on the input box, we send
the content of the input box to the server - A thread is created to receive the data from the
the server - The main thread is used to handle the Clients UI
48Chat Client Sample Code
- import java.io.
- import java.net.
- import javax.swing.
- import java.awt.
- import java.awt.event.
- public class ChatClient extends JFrame implements
Runnable, WindowListener, ActionListener - protected String host
- protected int port
- protected String username
- protected JTextArea output
- protected JTextField input
- protected DataInputStream dataIn
- protected DataOutputStream dataOut
- protected Thread listener
- public ChatClient(String host, int port, String
username) - super("ChatClient " host '' port ""
- " (" username ")")
- this.host host
- this.port port
49- public synchronized void start() throws
IOException - if (listener null)
- Socket socket new Socket(host, port)
- try
- dataIn new DataInputStream(
- new BufferedInputStream(
- socket.getInputStream()))
- dataOut new DataOutputStream(
- new BufferedOutputStream(
- socket.getOutputStream()))
- catch (IOException ex)
- socket.close()
- throw ex
-
- listener new Thread(this)
- listener.start()
- makeChatUI()
-
-
50- public synchronized void stop() throws
IOException - hide()
- if (listener ! null)
- listener.interrupt()
- listener null
- dataOut.close()
-
-
- public void run()
- try
- while (!Thread.interrupted())
- String line dataIn.readUTF()
- output.append(line "\n")
-
- catch (IOException ex)
- handleIOException(ex)
-
-
51- protected void makeChatUI()
- input new JTextField(30)
- input.addActionListener(this)
- output new JTextArea(8,30)
- output.setEditable(false)
- Container c getContentPane()
- c.add(new JScrollPane(output),
BorderLayout.CENTER) - c.add(input, BorderLayout.SOUTH)
- addWindowListener(this)
- pack()
- show()
-
- protected synchronized void handleIOException(IOE
xception ex) - if (listener ! null)
- output.append(ex "\n")
- input.setVisible(false)
- validate()
- if (listener ! Thread.currentThread())
- listener.interrupt()
52- public void windowOpened(WindowEvent event)
- input.requestFocus()
-
- public void windowClosing(WindowEvent event)
- try
- stop()
- catch (IOException ex)
- ex.printStackTrace()
-
-
- public void windowClosed(WindowEvent event)
- public void windowIconified(WindowEvent event)
- public void windowDeiconified(WindowEvent event)
- public void windowActivated(WindowEvent event)
- public void windowDeactivated(WindowEvent event)
53- public void actionPerformed(ActionEvent event)
- try
- input.selectAll()
- dataOut.writeUTF(username" "
- event.getActionCommand())
- dataOut.flush()
- catch (IOException ex)
- handleIOException(ex)
-
-
- public static void main(String args) throws
IOException - if ((args.length ! 2) (args0.indexOf('')
lt 0)) - throw new IllegalArgumentException(
- "Syntax ChatClient lthostgtltportgt
ltusernamegt") - int idx args0.indexOf('')
- String host args0.substring(0, idx)
- String username args1
- int port Integer.parseInt(args0.substring(id
x 1))
54Structure of UDP Client-Server
- UDP Server
- Create a datagram packet to hold the incoming
packet - Create a daragram socket
- Use the socket to receive a packet
- Close the socket
- UDP Client
- Prepare the packet by specifying the destination
address, port and data - Create a datagram socket
- Use the socket to send the packet
- Close the socket
55UDP Connection in Java Datagram Packet
- Datagram packets (java.net.DatagramPacket) are
used to package the data we want to send. - DatagramPacket(byte buf, int length, InetAdress
address, int port) - Constructor used to send message
- buf message content
- length message length (per packet)
- address and port destination of the message
- DatagramPacket(byte buf, int length)
- Constructor to be used to receive others message
- Address and port number can be retrieved from the
received packet
56Datagram Socket and Packet Methods
- DatagramSocket provides methods to receive and
send a packet - void receive(DatagramPacket data)
- void send (DatagramPacket data)
- DatagramPacket provides methods to set and
inquire about the status of the packet. For
example, - int getPort( ) / void setPort(int port)
- InetAddress getAddress( ) / void
setAddress(InetAddress address) - int getLength( ) / void setLength(int length)
57Datagram Packet Length and Exceptions
- Datagram packet length has different meaning from
time to time - Before a packet is sent, the length field
represents the size of buffer - After returning from receive method, the length
field represents the size received of packet - Thus, it is important to reset the length of the
packet if the same packet is used each time - Possible exceptions of DatagramPacket
- IllegalArgumentException when the packet length
is shorter than the length of message contents - IOException if there is transmission error
- SecurityException if the caller does not have
the access to the method
58Steps to Create a Datagram Server
- Create a DatagramSocket object
- Create a buffer for incoming datagrams
- Create a DatagramPacket object for the incoming
datagrams - Accept an incoming datagram
- Accept the sender's address and port from the
packet - Retrieve the data from the buffer
- Create the response datagram
- Send the response datagram
- Close the DatagramSocket
59UDP EchoServer Code Sample
- import java.io.
- import java.net.
- public class UDPEchoServer
- private static final int PORT 11111
- private static DatagramSocket dgramSocket
- private static DatagramPacket inPacket,
outPacket - private static byte buffer
- public static void main(String args)
- System.out.println("Opening port...\n")
- try
- dgramSocket new DatagramSocket(PORT) //Step
1. - catch(SocketException e)
- System.out.println("Unable to attach to
port!") - System.exit(1)
-
- run()
-
60- private static void run()
- try
- String messageIn,messageOut
- int numMessages 0
- do
- buffer new byte256 //Step 2.
- inPacket new DatagramPacket(buffer,
buffer.length) //Step 3. - dgramSocket.receive(inPacket) //Step 4.
- InetAddress clientAddress
inPacket.getAddress() - int clientPort inPacket.getPort()//Step 5.
- messageIn new String(inPacket.getData(),
0, inPacket.getLength()) //Step 6. - System.out.println("Message received.")
- numMessages
- messageOut ("Message " numMessages
" " messageIn) - outPacket new DatagramPacket( messageOut
.getBytes(), messageOut.length(), clientAddres
s, clientPort) //Step 7. - dgramSocket.send(outPacket) //Step 8.
- while (true)
- catch(IOException e)
- e.printStackTrace()
61Steps to Create a Datagram Client
- Create a DatagramSocket object
- Create the outgoing datagram
- Send the datagram message
- Create a buffer for incoming datagrams
- Create a DatagramPacket object for the incoming
datagrams - Accept an incoming datagram
- Retrieve the data from the buffer
- Close the DatagramSocket.
62UDP Echo Client Sample Code
- import java.io.
- import java.net.
- public class UDPEchoClient
- private static String host
- private static final int PORT 11111
- private static DatagramSocket dgramSocket
- private static DatagramPacket inPacket,
outPacket - private static byte buffer
- public static void main(String args)
- if(args.length 1)
- host args0
- else
- System.out.println( "Usage java
UDPEchoClient lthostnamegt") - System.exit(1)
-
- run()
-
63- private static void run()
- try
- dgramSocket new DatagramSocket() //Step 1.
- BufferedReader userEntry new
BufferedReader( new InputStreamReader(System.in
)) - String message"", response""
- do
- System.out.print("Enter message ")
- message userEntry.readLine()
- if (!message.equals("CLOSE"))
- outPacket new DatagramPacket( message.
getBytes(), message.length(), host,
PORT) //Step 2. - dgramSocket.send(outPacket) //Step 3.
- buffer new byte256 //Step 4.
- inPacket new DatagramPacket(
- buffer, buffer.length) //Step 5.
- dgramSocket.receive(inPacket) //Step 6.
- response new String(inPacket.getData(),
0, inPacket.getLength()) //Step 7. - System.out.println("\nSERVERgt "response)
-
- while (!message.equals("CLOSE"))