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

Prepared by: Eng/ Basma Elshoky

Section 4: Socket
Part II: socket for servers

TCP/IP (Transmission Control Protocol/Internet Protocol) is a suite of


communication protocols used to interconnect network devices on the internet. It
provides end-to-end communication specifying how data should be packetized,
addressed, transmitted, routed, and received at the destination.

Firstly, lets discuss the layers of the TCP/IP protocol stack and their corresponding
Java modules. Then explain socket server with an example for TCP/IP protocol.

Application Layer: This layer includes protocols like HTTP, FTP, SMTP, etc.,
which are used by applications to communicate over the network. In Java, you
interact with application layer protocols using various classes like
HttpURLConnection for HTTP, FTPClient for FTP, etc.
Transport Layer: The transport layer provides end-to-end communication between
the communicating hosts and ensures data delivery. TCP (Transmission Control
Protocol) and UDP (User Datagram Protocol) are the most common protocols at this
layer. In Java, you use Socket and ServerSocket classes for TCP communication and
DatagramSocket and DatagramPacket classes for UDP communication.
Internet Layer: This layer is responsible for routing packets across different
networks. IP (Internet Protocol) is the primary protocol used at this layer. In Java,
you don't typically interact directly with this layer, as lower-level networking
operations are abstracted away by higher-level APIs.
Link Layer: The link layer deals with the physical connection between devices
and the transmission of data frames. It includes protocols like Ethernet, Wi-Fi, etc.
Java doesn't provide direct APIs for interacting with the link layer, as it's usually
handled by the operating system and network drivers.
Prepared by: Eng/ Basma Elshoky

ServerSocket

ServerSocket represents a server-side endpoint that listens for incoming client


connections. It accepts connections and provides input and output streams for each
connection.

ServerSocket class is used to create a server-side socket that listens for incoming
client connections. Constructors & Methods:

Constructor Description
ServerSocket(int port) Creates a server socket bound to the specified port.
ServerSocket(int port, int Creates a server socket bound to the specified port, with a
backlog) specified backlog. The backlog is the maximum number
of pending connections the queue will hold.
ServerSocket(int port, int backlog, Creates a server socket bound to the specified port, with a
InetAddress bindAddr) specified backlog and network interface.
Prepared by: Eng/ Basma Elshoky

Method Description
bind(SocketAddress endpoint) Binds the server socket to a specific address (IP address
and port number).
close() Closes the server socket. Any pending client connections
will be terminated.
getInetAddress() Returns the address to which the socket is bound.
getLocalPort() Returns the port number on which this socket is listening.
setSoTimeout(int timeout) Sets the timeout in milliseconds for how long the accept()
method will block. If a connection is not established
within the timeout period, a SocketTimeoutException is
thrown.
getSoTimeout() Returns the timeout in milliseconds for how long the
accept() method will block.
setReuseAddress(boolean on) Sets the SO_REUSEADDR socket option. This allows
the socket to be bound even if there is a previous
connection in the TIME_WAIT state.
getReuseAddress() Returns whether the SO_REUSEADDR socket option is
enabled.
getChannel() Returns the server socket's ServerSocketChannel if
available.
setPerformancePreferences(int Sets performance preferences for connection time,
connectionTime, int latency, int latency, and bandwidth. This can influence the system's
bandwidth): choice of underlying implementation.
Prepared by: Eng/ Basma Elshoky

Additional classes:

InputStream and OutputStream: These classes represent streams for reading and
writing binary data. They are the fundamental building blocks for network streams.

Reader and Writer: These classes represent streams for reading and writing
character-based data. They are built on top of InputStream and OutputStream and
provide support for character encoding.

DataInputStream and DataOutputStream: These classes provide methods for


reading and writing Java’s primitive data types and strings in a binary format.

BufferedOutputStream: This class stores written data in a buffer (a protected byte


array field named buf) until the buffer is full or the stream is flushed

BufferedInputStream: This class also has a protected byte array named buf that
serves as a buffer. It does not declare any new methods of its own. It only overrides
methods from InputStream.

BufferedReader: BufferedReader is a class in Java that reads text from a


character-input stream, buffering characters to provide efficient reading of
characters, arrays, and lines.

For more info: Watch chapter 1 from this link: https://toalhussein.notion.site/Java-


IO-And-Network-Programming-912f2fcbed01469d8426cb5c42234487

Example 1:

Checks for ports on the local machine by attempting to create ServerSocket objects
on them and seeing on which ports that fails. If you’re using Unix and are not
running as root, this program works only for ports 1,024 and above.
Prepared by: Eng/ Basma Elshoky

for (int port = 1; port <= 65535; port++) {


try {
ServerSocket server = new ServerSocket(port);
System.out.println("Available : " + port + ".");
}
catch (IOException ex) {
System.out.println("There is a server on port " + port + ".");
} // end catch
}
Prepared by: Eng/ Basma Elshoky

create a server socket on port 130 that would hold up to 100 incoming
connection requests in the queue, you would write

Example: demonstrating how to establish a TCP connection using Java

String serverHostname = "localhost"; // Change this to the server's


hostname or IP address
int serverPort = 80; // Change this to the server's port

try (Socket socket = new Socket(serverHostname, serverPort);


PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new
InputStreamReader(socket.getInputStream()))) {
// Send data to the server
out.println("Hello, server!");
// Receive data from the server
String response = in.readLine();
System.out.println("Server response: " + response);
} catch (UnknownHostException e) {
System.err.println("Unknown host: " + serverHostname);
} catch (IOException e) {
System.err.println("Error communicating with the server: " +
e.getMessage());
}
Prepared by: Eng/ Basma Elshoky
Prepared by: Eng/ Basma Elshoky
Prepared by: Eng/ Basma Elshoky

Homework Task:

Watch chapter 2 from this link: https://toalhussein.notion.site/Java-IO-And-


Network-Programming-912f2fcbed01469d8426cb5c42234487

Then apply CH02_VID07_Build Server Client Application in Java .”code with screen of
result from your PC”

You might also like