[go: up one dir, main page]

0% found this document useful (0 votes)
11 views63 pages

Lecture_6

The document explains the differences between using URLConnection and sockets for network communication, highlighting that URLConnection is suited for HTTP/HTTPS while sockets provide low-level control for various protocols. It details socket operations, how to create and connect sockets in Java, and methods for reading from and writing to servers. Additionally, it covers socket options and configurations that can optimize network performance.

Uploaded by

Dipesh Khatiwada
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views63 pages

Lecture_6

The document explains the differences between using URLConnection and sockets for network communication, highlighting that URLConnection is suited for HTTP/HTTPS while sockets provide low-level control for various protocols. It details socket operations, how to create and connect sockets in Java, and methods for reading from and writing to servers. Additionally, it covers socket options and configurations that can optimize network performance.

Uploaded by

Dipesh Khatiwada
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 63

NETWORK PROGRAMMING

SOCKET FOR CLIENTS


Question: why do I need socket when I can communicate using URLConnection class ?
Answer: The URLConnection class and sockets serve different purposes and have distinct use
cases in network communication

URLConnection is a higher-level abstraction for communicating with URLs over


HTTP/HTTPS
It is easier to use for simple HTTP requests like GET and POST.

Methods like setRequestMethod("GET"), setRequestProperty(), and getResponseCode() help


handle common HTTP tasks
Automatically manages HTTP headers and cookies, making requests and handling responses
easier
Ideal for web page fetching, REST API calls, or any other HTTP/HTTPS communication
Sockets provide a low-level communication mechanism, allowing more control over the data
being sent and received

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

Use URLConnection When:


Your application communicates with web servers using standard HTTP/HTTPS protocols,
URLConnection offers a straightforward and effective solution
Use Sockets When:
You need to implement non-HTTP protocols or require finer control over network
communication
Your application demands low latency and real-time data exchange, such as in games or live
streaming
Introduction to Socket
A socket is simply an end point of communications between the machines

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

Java programs normally use client sockets in the following fashion:


 The program creates a new socket with a Socket() constructor
 The socket attempts to connect to the remote host
 Once the connection is established, the local and the remote hosts get input and output
streams from the socket and use those streams to send data to each other. This connection is
full-duplex ; both hosts can send data and receive data simultaneously
 When the transmission of data is complete, one or both sides close the connection
Creating a Socket
To create a client socket in Java, you need to use the Socket class from the java.net package

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.

What This Code Does


Connects to a Time Server: The application connects to a server that implements the Daytime
Protocol
Reads Time Information: It reads the server's response, which is a string containing the current
time and date
Prints the Result: The response is printed to the console, showing the current time according to
the server
This code establishes a TCP connection to "example.com" on port 80
Port 80 is the default port for HTTP traffic, where web servers listen for incoming HTTP
requests.

The PrintWriter is used to send text data to the server.


The autoFlush parameter is set to true, which means that the output stream is automatically
flushed whenever println, printf, or format is called. This ensures that data is sent immediately.

The InputStream is wrapped in an InputStreamReader and then in a BufferedReader, which


makes it efficient to read lines of text from the server's response.

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

Example: Next Slide


In the provided example, writing to the server involves sending the "Close" command to the
dict.org server using the DICT protocol

Steps to Write to a Server


Establish a Connection

A socket connection is established between the client and the server


The client uses the server's hostname and port number to connect

Obtain the Output Stream


Once the connection is established, the client obtains an output stream from the socket.
This stream is used to send data to the server.
Client speaks first, so ask for the OutputStream using getOutputStream()
Create a Writer
An OutputStreamWriter or another suitable writer is created to convert characters into bytes,
which can be sent over the network. The writer is connected to the output stream

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

Flush the Writer


The writer is flushed to ensure that all buffered data is sent immediately. This is important for
ensuring that the server receives the complete message without delay.
Constructing and Connecting Sockets: Basic Constructors:
public Socket(String host, int port) is used to create a socket and connect it to the specified
remote host at the specified port

public Socket(String host, int port) throws UnknownHostException, IOException

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

public Socket(InetAddress host, int port) throws IOException

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

Example: Next Slide


Constructing without connecting:
All the constructors we have talked so far both create the socket object and open a network
connection to a remote host

If you give no arguments to the socket constructor, it has no where to connect to

public Socket()

You can connect later by passing SocketAddress to one of the connect() method

Example: Next Slide


Socket Address:
This class represents connection end point

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

public SocketAddress getRemoteSocketAddress()


public SocketAddress getLocalSocketAddress()

Example: Next Slide


Getting Informations about Socket:
Socket object have several properties that are accessible through getter methods

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

Example: Next Slide


2. Remote port
getPort() method is used to retrieve the port number to which a socket is connected or bound
This method is available on both Socket and ServerSocket objects, providing information
about the local or remote port of a network connection

Example: Next Slide


3. Local Address
public InetAddress getLocalAddress()
getLocalAddress() method is used to retrieve the local IP address to which a socket is bound.
This method is available on both Socket and ServerSocket objects and provides information
about the local endpoint of a network connection

Example: Next Slide


4. Local Port
public int getLocalPort()

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.

Example: Next Slide


public boolean isClosed()
This method checks whether the socket has been closed or not
Once a socket is closed, it cannot be reopened for further communication

public boolean isConnected()


This method checks whether the socket is connected to a remote endpoint or not

Example: Next Slide


toString()
This method for a Socket object typically returns a string that includes the following
information:

Local and remote IP addresses


Local and remote port numbers

Example: Next Slide


Setting Socket Options:
TCP_NoDelay

setTcpNoDelay(boolean on)

public void setTcpNoDelay(boolean on)


Parameters:
on: true to enable TCP no-delay (Nagle's algorithm is disabled), false to disable it (Nagle's
algorithm is enabled).
Description: This method enables or disables the TCP no-delay option for the socket. When
TCP no-delay is enabled (on is true), it means that the Nagle's algorithm is disabled. Nagle's
algorithm aims to reduce the number of small packets sent over the network by buffering
small amounts of outgoing data until a full-sized packet can be sent. Disabling it can
reduce latency for small packets but may increase network traffic.
getTcpNoDelay():
public boolean getTcpNoDelay()
Return Type: boolean
Description: This method retrieves the current state of the TCP no-delay option for the socket
It returns true if TCP no-delay is enabled (Nagle's algorithm is disabled), and false if it is
disabled (Nagle's algorithm is enabled)

Example: Next Slide


Nagle's Algorithm: By default, TCP sockets in Java have Nagle's algorithm enabled
(setTcpNoDelay(false)), which means that small outgoing packets are buffered until enough
data is accumulated or a timeout occurs.
Enabling TCP no-delay (setTcpNoDelay(true)) disables Nagle's algorithm, causing each write
operation to be sent immediately, which can reduce latency for small messages but might
increase network traffic.

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

Example: Next Slide


SO_TIMEOUT
This option is used to specify a timeout for socket operations
This timeout specifies the maximum time (in milliseconds) that a read or accept operation on a
socket will block
If the timeout expires, a java.net.SocketTimeoutException is thrown

setSoTimeout(int timeout): Sets the SO_TIMEOUT with the specified timeout value
getSoTimeout(): Retrieves the current SO_TIMEOUT value

Example: Next Slide


SO_RCVBUF
It is a socket option that specifies the receive buffer size for a socket
The receive buffer is the amount of memory allocated for storing incoming data before it is
read by the application
Adjusting the receive buffer size can improve performance in certain network conditions

setReceiveBufferSize(int size): Sets the SO_RCVBUF to the specified size in bytes


getReceiveBufferSize(): Retrieves the current SO_RCVBUF value in bytes

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

setSendBufferSize(int size): Sets the SO_SNDBUF to the specified size in bytes


getSendBufferSize(): Retrieves the current SO_SNDBUF value in bytes

Example: Next Slide


SO_KEEPALIVE
It socket option is used to enable or disable the TCP keepalive feature
This feature helps in detecting broken connections by sending periodic keepalive probes to the
remote peer
If the remote peer does not respond, the connection is considered broken, and an error is
reported to the application

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)

Example: Next Slide


OOBLINE
This option is related to Out-of-Band (OOB) data in TCP connections.
In Java, handling OOB data is managed using the Socket class methods for sending urgent
data

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

Example: Next Slide


WHOIS Protocol
The WHOIS protocol is a query and response protocol widely used for querying databases
that store information about the registered users or assignees of an Internet resource, such as a
domain name, an IP address block

Simple Text-Based Protocol: WHOIS operates over TCP and communicates in a simple text
format

Port 43: WHOIS queries are typically sent to port 43

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

Example: Next Slide

You might also like