Socket programming
Sockets for Clients
A socket
is a connection between two hosts.
Operations
• 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 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 and
receive data simultaneously.
• When the
transmission of data is complete, one or both sides close the connection.
Constructors
1. public
Socket (String host, int port) throws UnknownHostException, IOException
This
constructor creates a TCP socket to the specified port on the specified host
and attempts to connect to the remote host.
2. public
Socket(InetAddress host, int port) throws IOException
This
constructor creates a TCP socket to the specified port on the specified host
and tries to connect. It differs by using an InetAddress object to specify the
host rather than a hostname.
Example: Find out which of the Ports at or Above
1,024 Seem to Be Hosting TCP Server
import
java.net.*; import java.io.*;
public
class PortScanner {
public static void main(String[] args) { String
host = "localhost";
if (args.length > 0) { host = args[0];
}
try {
InetAddress
theAddress = InetAddress.getByName(host); for (int i = 1024; i < 65536; i++)
{
try {
Socket
theSocket = new Socket(theAddress, i);
System.out.println("There
is a server on port "
+ i +
" of " + host);
}
catch
(IOException e) {
// must
not be a server on this port }} // end for
} // end
try
catch (UnknownHostException e) {
System.err.println(e);
}
} // end
main } // end PortScanner
Example: Echo Client import
java.net.*; import java.io.*;
public
class EchoClient {
public static void main(String[] args) { String
hostname = "localhost"; if (args.length > 0) {
hostname
= args[0];
}
PrintWriter
out = null; BufferedReader br = null; try {
Socket s=
new Socket (hostname, 7);
br= new
BufferedReader(new InputStreamReader(s.getInputStream( )));
BufferedReader
in = new BufferedReader(new InputStreamReader(System.in)); out = new
PrintWriter(s.getOutputStream( ));
System.out.println
("Connected to echo server"); while (true) {
String
theLine = in.readLine( ); if (theLine.equals(".")) break;
out.println(theLine);
out.flush(
); System.out.println(networkIn.readLine( ));
}
} // end
try
catch (IOException e) { System.err.println (e);
}
} // end
main
} // end
EchoClient
Sockets for Servers
A ServerSocket runs on the server and listens for incoming TCP
connections. Each ServerSocket listens on a particular port on the server
machine. When a client Socket on a remote host attempts to connect to that
port, the server wakes up, negotiates the connection between the client and the
server, and opens a regular Socket between the two hosts.
Operations
A new
ServerSocket is created on a particular port using a ServerSocket( ) constructor.
• The
ServerSocket listens for incoming connection attempts on that port using its
accept( ) method. accept( ) blocks until a client attempts to make a
connection, at which point accept( ) returns a Socket object connecting the
client and the server.
• Depending
on the type of server, either the Socket's getInputStream( ) method,
getOutputStream( ) method, or both are called to get input and output streams
that communicate with the client.
• The
server and the client interact according to an agreed-upon protocol until it is
time to close the connection.
• The server,
the client, or both close the connection.
• The
server returns to step 2 and waits for the next connection.
Constructors
1. public
ServerSocket(int port) throws IOException, BindException
2. public
ServerSocket(int port, int queueLength) throws IOException, BindException
3. public ServerSocket(int port, int queueLength,
InetAddress bindAddress) throws IOException
Example: Look for Local Ports
import
java.net.*; import java.io.*;
public
class LocalPortScanner {
public
static void main(String[] args) {
for (int
port = 1; port <= 65535; port++)
{ try {
// the next
line will fail and drop into the catch block if
// there is
already a server running on the port ServerSocket server = new
ServerSocket(port);
}
catch
(IOException e) {
System.out.println("There
is a server on port " + port + ".");
} // end try } // end for
}
}
The
program checks for ports on the local machine by attempting to create
ServerSocket objects on them and seeing on which ports that fails.
Datagram Packet
UDP
datagram is represented by an instance of the DatagramPacket class public final
class DatagramPacket extends Object
Constructors
Receiving datagram
1. public
DatagramPacket(byte[] buffer, int length)
When a
socket receives a datagram, it stores the datagram's data part in buffer
beginning at buffer[0] and continuing until the packet is completely stored or
until length bytes have been written into the buffer.
2. public
DatagramPacket(byte[] buffer, int offset, int length)
When a
socket receives a datagram, it stores the datagram's data part in buffer
beginning at buffer[offset] and continuing until the packet is completely
stored or until length bytes have been written into the buffer.
Sending datagram
1. public
DatagramPacket(byte[] data, int length, InetAddress destination, int port)
2. public
DatagramPacket(byte[] data, int offset, int length, InetAddress destination,
int port)
Each
constructor creates a new DatagramPacket to be sent to another host. The packet
is filled with length bytes of the data array starting at offset or if offset
is not used. If you try to construct a DatagramPacket with a length that is
greater than data.length, the constructor throws an IllegalArgumentException.
Datagram Socket
To send
or receive a Datagram Packet, need to open a datagram socket.
Constructors
1. public
DatagramSocket( ) throws SocketException
This
constructor creates a socket that is bound to an anonymous port.
2. public
DatagramSocket(int port) throws SocketException
This
constructor creates a socket that listens for incoming data grams on a specific
port, specified by the port argument.
Sending and Receiving Data grams
1. public
void send(DatagramPacket dp) throws IOException
Once a
DatagramPacket is created and a DatagramSocket is constructed, send the packet
by passing it to the socket's send( ) method.
2. public
void receive(DatagramPacket dp) throws IOException
This
method receives a single UDP datagram from the network and stores it in the
pre-existing DatagramPacket object
Related Topics
Privacy Policy, Terms and Conditions, DMCA Policy and Compliant
Copyright © 2018-2023 BrainKart.com; All Rights Reserved. Developed by Therithal info, Chennai.