Lecture_6
Lecture_6
They are suitable for implementing protocols other than HTTP, such as FTP, SMTP, or
custom protocols.
Sockets allow bi-directional communication and can be used for real-time applications
It is one end point of a two way communcation link between two programs running on the
network
The java.net package in the java platform provides a class, Socket, that implements one side of
a two way communications between java program and another program on the network
A socket can perform seven basic operations:
Connect to a remote machine
Send data
Receive data
Close a connection
Bind to a port
Listen for incoming data
Accept connections from remote machines on the bound port
Java‘s socket class, which is used by both the client and servers, has methods that correspond to
the first four of these operations
The last three operations are only needed by the servers, which will wait for clients to connect
to them
They are implemented by ServerSocket class, which will be discussed in the next chapter
Syntax:
Socket socket = new Socket(hostname, port);
Example:
Socket socket=new Socket("127.0.0.1",5000);
The hostname (localhost) and port number (12345) of the server are specified
A Socket object is created and connected to the server using the specified hostname and port
Reading from servers with sockets
To read data from a server using sockets, use the Socket class to connect to the server, and then
use input streams to read data from the server
Steps:
Import Required Classes
Specify the hostname (or IP address) and port number of the server
Read data from the server
This is a simple Java application that connects to a time server using a socket and reads data
from it.
Specifically, it connects to "time.nist.gov" on port 13, which is a public server that provides the
current time using the Daytime Protocol.
This loop reads lines from the server until the end of the stream is reached. Each line of the
response is printed to the console.
The server's response typically includes:
Status Line: The HTTP version, status code, and status message.
Headers: Key-value pairs providing metadata about the response (e.g., Content-Type, Content-
Length).
Body: The actual content of the response, such as the HTML of a webpage.
This code example illustrates how to manually interact with a web server using sockets to
send an HTTP request and read the response
Writing to the server with sockets
Writing to a server in the context of socket programming means sending data from a client
application to a server application over a network connection
This is typically done through an output stream associated with a socket connection
When you write data to this output stream, it gets transmitted over the network to the server,
which can then read and process this data
Send Data
The client writes data (e.g., commands, messages) to the writer.
The writer converts the characters to bytes and writes them to the output stream.
The data is transmitted over the network to the server
host: A String representing the hostname or IP address of the remote server to which you want
to connect.
For example, this could be "example.com" or "192.168.1.1".
port: An int representing the port number on the remote server to which you want to connect.
Port numbers range from 0 to 65535, but ports below 1024 are typically reserved for well-
known services (e.g., HTTP uses port 80).
UnknownHostException: This exception is thrown if the IP address of the host could not be
determined, meaning the hostname cannot be resolved
IOException: This exception is thrown if an I/O error occurs when creating the socket.
For example, this could happen if the server is not reachable, the connection is refused, or the
socket could not be created
The constructor attempts to resolve the given hostname to an IP address. If the hostname
cannot be resolved, an UnknownHostException is thrown
The constructor creates a new socket. If the creation of the socket fails for any reason (e.g.,
lack of system resources, invalid port number), an IOException is thrown
The constructor attempts to connect the socket to the specified remote host at the given port.
If the connection cannot be established (e.g., network issues, server not available), an
IOException is thrown.
WAP to find out which of the first 1024 ports seems to be hosting tcp servers on the specified
host(the localhost by default)
public Socket(InetAddress host, int port):
public Socket(InetAddress host, int port) is used to create a socket and connect it to a
specified remote host identified by its IP address (InetAddress) and a port number
host: An InetAddress object representing the IP address of the remote host to which you want
to connect. This can be obtained using methods like InetAddress.getByName(String
hostname) to resolve a hostname to an IP address
port: An int representing the port number on the remote host to which you want to connect.
Port numbers range from 0 to 65535, but ports below 1024 are typically reserved for well-
known services
The Socket(InetAddress host, int port) constructor is useful when you want to connect to a
remote server using its IP address instead of its hostname
This is particularly useful when you already have the IP address of the server or when you
want to avoid the overhead of hostname resolution
public Socket()
You can connect later by passing SocketAddress to one of the connect() method
The socket class offers two methods that returns socket address objects ,
getRemoteSocketAddress() returns the address of the system being connected to and
getLocalSocketAddress() returns the address from which the connection is made
1. Remote address
public InetAddress getInetAddress()
getInetAddress() method is used to retrieve the local or remote IP address associated with a
socket
This method is available on both Socket and ServerSocket objects, providing information
about the local or remote endpoint of a network connection
getLocalPort() method is used to retrieve the local port number to which a socket is bound.
This method is available on both Socket and ServerSocket objects and provides information
about the local endpoint's port of a network connection.
setTcpNoDelay(boolean on)
Impact: The decision to enable or disable TCP no-delay depends on the specific requirements
of your application.
For latency-sensitive applications where small packets need to be sent quickly, enabling TCP
no-delay may be beneficial.
However, it's essential to consider potential impacts on network efficiency and throughput.
SO_LINGER
setSoLinger and getSoLinger are methods used to configure the socket's linger option.
This setting controls the behavior of the socket when it is closed, specifically how it handles
unsent data
setSoLinger(int on, int linger)
public void setSoLinger(boolean on, int linger)
Parameters:
on: true to enable the linger option, false to disable it
linger: The linger time in seconds. If on is true, this parameter specifies the amount of time
to wait for data to be sent before closing the socket.
If on is false, the socket will not wait for unsent data and will close immediately.
This method sets the linger option for the socket.
When the linger option is enabled (on is true), the socket will wait for the specified amount of
time (linger) to send any unsent data before closing
If linger is set to 0, the socket closes immediately
getSoLinger()
public int getSoLinger()
Description: This method retrieves the current setting of the socket’s linger option.
It returns an integer value. If the linger option is disabled, it returns -1. If enabled, it returns
the linger time in seconds
setSoTimeout(int timeout): Sets the SO_TIMEOUT with the specified timeout value
getSoTimeout(): Retrieves the current SO_TIMEOUT value
Adjusting the receive buffer size can improve performance by accommodating network
conditions and application requirements. A larger buffer is useful for high-latency networks or
when receiving large amounts of data, while a smaller buffer can save memory in constrained
environments
Example: Next Slide
SO_SNDBUF
It is a socket option that specifies the send buffer size for a socket
The send buffer is the amount of memory allocated for storing outgoing data before it is
transmitted over the network
Adjusting the send buffer size can improve performance in certain network conditions by
managing how much data can be queued for transmission
setKeepAlive(boolean on): Enables (true) or disables (false) the TCP keepalive option
getKeepAlive(): Retrieves the current state of the TCP keepalive option (enabled or disabled)
In TCP, OOB data is a way to send urgent data that should be processed immediately, ahead of
any other normal data in the stream
This is typically used for signalling or control messages
Simple Text-Based Protocol: WHOIS operates over TCP and communicates in a simple text
format
Query and Response: The client sends a query string to the WHOIS server, which responds
with the information about the queried resource
You can use the WHOIS protocol to obtain information about a domain or IP address
This can be done using command-line tools, web-based WHOIS lookup services, or by
implementing your own WHOIS client