Lesson 12. Implementing the Client-Server Model in Java

Lecture 8 min.



Fundamentals of Building Network Applications in Java

Lecture Outline

  • Transport layer protocols
  • The concept of a socket
  • The java.net package
  • The Socket and ServerSocket classes
  • The DatagramPacket and DatagramSocket classes
  • The URL class



The OSI Model

  • Application layer
  • Presentation layer
  • Session layer
  • Transport layer
  • Network layer
  • Data link layer
  • Physical layer


Lesson 12. Implementing the Client-Server Model in Java

.
Transmission Control Protocol (TCP) is a connection-based protocol that provides reliable data transfer between two computers while preserving the order of the data

Used in: HTTP, FTP, Telnet, etc.

Lesson 12. Implementing the Client-Server Model in Java

User Datagram Protocol (UDP) is a connectionless protocol that sends independent packets of data, called datagrams, from one computer to another with no guarantee of their delivery

Lesson 12. Implementing the Client-Server Model in Java

The Client-Server Model

How it works

  • Each side of the virtual connection is called a "socket"
  • The server process is initialized at startup and then sits idle, waiting for a request from a client
  • The client process sends a request to establish a connection with the server, asking it to perform a certain function. Types of server applications
  • Iterative (sequential) request-processing server
  • Concurrent (parallel) request-processing server


The concept of a port A computer (usually) has only one physical connection to the network. The connection is described, for example, by an IP address (currently 32 or 128 bits). How can information for different applications be told apart? A.V.
Lesson 12. Implementing the Client-Server Model in Java

A socket is bound to a port

A port is described by a 16-bit number

Ports 0-1023 are reserved

TCP orUDP portapp port # data Packet Data

The Socket Interface

In the 1980s, the American government agency for supporting research projects (ARPA) funded the implementation of the TCP/IP protocols for UNIX at the University of California in

Berkeley. An application programming interface for TCP/IP network applications (TCP/IP API) was developed

TCP/IP sockets or Berkeley sockets

Lesson 12. Implementing the Client-Server Model in Java

Relationship with the file system. TCP/IP within UNIX. The socket interface works through UNIX system calls. UNIX I/O system calls look like a sequential cycle:

  • open
  • read/write
  • close

There is no distinction between files and external devices


Problems of Network I/O

The client-server model does not fit the UNIX I/O system

  • There are no passive I/O operations
  • It cannot establish connections
  • A fixed file address is used
  • The connection to a file is available throughout the entire write-read cycle. For connectionless protocols a fixed address is a problem: when a datagram is sent there is an address, but no connection


The Socket Abstraction

A network connection is the process of transferring data over a network between two computers or processes

A socket is an endpoint of data transfer

For programs, a socket is one end of a network connection

To establish a connection, each network program must have its own socket

Communication between two sockets can be connection-oriented

Communication between two sockets can be connectionless

A socket is associated with a port number

Lesson 12. Implementing the Client-Server Model in Java

The socket abstraction serverport client connection request serverport p o r t clientport connection

And What About Java?

Sockets are encapsulated in instances of special classes

All low-level interaction is hidden from the user

There is a family of classes that provide socket configuration and socket handling

The java.net Package

Addressing

Establishing a TCP connection

Sending/receiving datagrams via UDP. Discovery/identification of network resources

Security: authorization / access rights

Addressing

IP addressing

Socket address InetAddress Inet4Address Inet6Address SocketAddress InetSocketAddress

Lesson 12. Implementing the Client-Server Model in Java

Lesson 12. Implementing the Client-Server Model in Java

Lesson 12. Implementing the Client-Server Model in Java

The Socket class. Implements the client socket and its functions

Constructors

  • Socket()
  • Socket(InetAddress address, int port)
  • Socket(InetAddress address, int port, InetAddress localAddr, int localPort)
  • Socket(String host, int port)
  • Socket(String host, int port, InetAddress localAddr, int localPort)

Methods

  • void close()
  • InetAddress getLocalAddress()
  • InputStream getInputStream()
  • OutputStream getOutputStream()
  • static void setSocketImplFactory(SocketImplFactory fac)
  • And others…

Lesson 12. Implementing the Client-Server Model in Java

Working with a client socket

  • Open the socket
  • Open an input stream and/or an output stream for the socket
  • Read from and write to the streams according to the established protocol of communication with the server
  • Close the input/output streams
  • Close the socket

Client example import java.io.*;

import java.net.*;

public class EchoClient { public static void main(String[] args) throws IOException { Socket echoSocket = null;

PrintWriter out = null;

BufferedReader in = null;

try { echoSocket = new Socket("taranis", 7);

out = new PrintWriter(echoSocket.getOutputStream(), true);

in = new BufferedReader(new InputStreamReader( echoSocket.getInputStream()));

} catch (UnknownHostException e) { System.err.println("Don't know about host: taranis.");

System.exit(1);

} catch (IOException e) { System.err.println("Couldn't get I/O for the connection to:" + "taranis.");

System.exit(1);

}

Client example BufferedReader stdIn = new BufferedReader( new InputStreamReader(System.in));

String userInput;

while ((userInput = stdIn.readLine()) != null) { out.println(userInput);

System.out.println("echo: " + in.readLine());

} out.close();

in.close();

stdIn.close();

echoSocket.close();

}}

Lesson 12. Implementing the Client-Server Model in Java

The ServerSocket class

Implements the server socket and its functions

Constructors

  • ServerSocket()
  • ServerSocket(int port)
  • ServerSocket(int port, int backlog)

Methods

  • void close()
  • Socket accept()
  • void bind(SocketAddress endpoint)
  • And others…

Creating a server socket

try { serverSocket = new ServerSocket(4444);

} catch (IOException e) { System.out.println( "Could not listen on port: 4444");

System.exit(-1);} Socket clientSocket = null;

try { clientSocket = serverSocket.accept();

} catch (IOException e) { System.out.println("Accept failed: 4444");

System.exit(-1);}

Lesson 12. Implementing the Client-Server Model in Java

Concurrent request-processing server

Stage 1: The client-server connection is established

Stage 2: The concurrent server hands control over to a child process

Stage 3: If another client's request arrives while a request is being processed, the concurrent server hands control over to a new child process

Client 1 Server Client 1 Child process 1 Server Client 1 Child process 1 Server Client 2 Child process 2

Lesson 12. Implementing the Client-Server Model in Java

Datagrams

A datagram is an independent, self-contained message sent over a network, whose delivery, arrival time (order) and content are not guaranteed. Datagrams can be used for both unicast and broadcast messaging

The DatagramPacket class. Instances of this class are prototypes of datagram messages

Constructors

  • DatagramPacket(byte[] buf, int offset, int length, InetAddress address, int port)
  • And others…

Methods

  • byte[] getData()
  • int getLength()
  • int getOffset()
  • SocketAddress getSocketAddress()
  • void setSocketAddress(SocketAddress address)
  • void setData(byte[] buf, int offset, int length)
  • And others…

The DatagramSocket class

Instances are connectionless sockets

Constructors

  • DatagramSocket()
  • DatagramSocket(int port, InetAddress laddr)
  • And others…

Methods

  • void bind(SocketAddress addr)
  • void close()
  • void connect(InetAddress address, int port)
  • void send(DatagramPacket p)
  • void receive(DatagramPacket p)
  • And others…

Sending datagrams

Lesson 12. Implementing the Client-Server Model in Java

Uniform Resource Locator

URL is the address of a resource on the Internet. Protocol name: the protocol used for communication. Host name: the name of the computer on which the resource is located. File name: the path to the file on the computer. Port number: the port number for the connection (optional). Reference: a reference to a named anchor (optional). It can be an absolute or a relative URL. gamelan = new URL("http", "www.gamelan.com", 80, "pages/Gamelan.network.html");
Lesson 12. Implementing the Client-Server Model in Java

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();

}}

Lesson 12. Implementing the Client-Server Model in Java

Reading from a URL connection 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();

}}

Writing to a URL connection import java.io.*;

import java.net.*;

public class Reverse { public static void main(String[] args) throws Exception { if (args.length != 1) { System.err.println("Usage: java Reverse" + "string_to_reverse");

System.exit(1);

} String stringToReverse = URLEncoder.encode(args , "US-ASCII");

URL url = new URL( "http://java.sun.com/cgi-bin/backwards");

Lesson 12. Implementing the Client-Server Model in Java

Writing to a URL connection URLConnection connection = url.openConnection();

connection.setDoOutput(true);

PrintWriter out = new PrintWriter( connection.getOutputStream());

out.println("string=" + stringToReverse);

out.close();

BufferedReader in = new BufferedReader( new InputStreamReader( connection.getInputStream()));

String inputLine;

while ((inputLine = in.readLine()) != null) System.out.println(inputLine);

in.close();

}}

Lesson 12. Implementing the Client-Server Model in Java

Lesson 12. Implementing the Client-Server Model in Java

See also

  • REST API
created: 2022-02-07
updated: 2026-09-29
131



Was this answer useful?
Choose a quick rating so we can improve the next answer for you.
How satisfied are you?


Comments

To leave a comment

If you have any suggestion, idea, thanks or comment, feel free to write. We really value feedback and are glad to hear your opinion.
To reply

Lectures and tutorial on "OOP and Practical JAVA"

Terms: OOP and Practical JAVA