Socket Programming in Java:
Java Socket programming is used for communication between the applications
running on different JRE.
Java Socket programming can be connection-oriented or connection-less.
Socket and ServerSocket classes are used for connection-oriented socket
programming and DatagramSocket and DatagramPacket classes are used for
connection-less socket programming.
The client in socket programming must know two information:
IP Address of Server, and
Port number.
1. Client-Side Programming
(a) Establish a Socket Connection: To connect to another machine we need a socket
connection. A socket connection means the two machines have information about each
other’s network location (IP Address) and TCP port. The java.net.Socket class represents a
Socket. To open a socket:
Socket socket = new Socket(“127.0.0.1”, 5000)
The first argument – IP address of Server. ( 127.0.0.1 is the IP address of
localhost, where code will run on the single stand-alone machine).
The second argument – TCP Port. (Just a number representing which application
to run on a server. For example, HTTP runs on port 80. Port number can be from
0 to 65535)
(b) Communication: To communicate over a socket connection, streams are used to both
input and output the data.
(c) Closing the connection: The socket connection is closed explicitly once the message to
the server is sent.
In the program, the Client keeps reading input from a user and sends it to the server until
“Over” is typed.
Java Implementation:
// A Java program for a Client
import java.io.*;
import java.net.*;
public class Client {
private Socket socket = null;
private DataInputStream input = null;
private DataOutputStream out = null;
public Client(String address, int port)
{
try {
socket = new Socket(address, port);
System.out.println("Connected");
// takes input from terminal
input = new DataInputStream(System.in);
// sends output to the socket
out = new DataOutputStream(
socket.getOutputStream());
}
catch (UnknownHostException u) {
System.out.println(u);
return;
}
catch (IOException i) {
System.out.println(i);
return;
}
// string to read message from input
String line = "";
// keep reading until "Over" is input
while (!line.equals("Over")) {
try {
line = input.readLine();
out.writeUTF(line);
}
catch (IOException i) {
System.out.println(i);
}
}
try {
input.close();
out.close();
socket.close();
}
catch (IOException i) {
System.out.println(i);
}
}
public static void main(String args[])
{
Client client = new Client("127.0.0.1", 5000);
}
}
2. Server Programming:
(a) Establish a Socket Connection: To write a server application two sockets are needed.
A ServerSocket which waits for the client requests (when a client makes a new
Socket())
A plain old Socket to use for communication with the client.
(b) Communication: getOutputStream() method is used to send the output through the
socket.
(c) Close the Connection : After finishing, it is important to close the connection by
closing the socket as well as input/output streams.
// A Java program for a Server
import java.net.*;
import java.io.*;
public class Server
{
private Socket socket = null;
private ServerSocket server = null;
private DataInputStream in = null;
public Server(int port)
{
try
{
server = new ServerSocket(port);
System.out.println("Server started");
System.out.println("Waiting for a client ...");
socket = server.accept();
System.out.println("Client accepted");
// takes input from the client socket
in = new DataInputStream(
new BufferedInputStream(socket.getInputStream()));
String line = "";
// reads message from client until "Over" is sent
while (!line.equals("Over"))
{
try
{
line = in.readUTF();
System.out.println(line);
}
catch(IOException i)
{
System.out.println(i);
}
}
System.out.println("Closing connection");
socket.close();
in.close();
}
catch(IOException i)
{
System.out.println(i);
}
}
public static void main(String args[])
{
Server server = new Server(5000);
}
}
ServerSocket Class:
ServerSocket Class is used for providing system-independent implementa on of the
server-side of a client/server Socket Connec on.
The constructor for ServerSocket throws an excep on if it can’t listen on the specified
port (for example, the port is already being used).
implementation:
1. Server-Side
// Java Program to implement ServerSocket class
// Server Side
import java.io.*;
import java.net.*;
public class MyServer {
public static void main(String[] args)
{
try {
ServerSocket ss = new ServerSocket(6666);
Socket soc = ss.accept();
DataInputStream dis
= new DataInputStream(soc.getInputStream());
String str = (String)dis.readUTF();
System.out.println("message= " + str);
ss.close();
}
catch (Exception e) {
System.out.println(e);
}
}
}
2. Client-Side
// Java Program to implement ServerSocket class
// Client - side
import java.io.*;
import java.net.*;
public class MyClient {
public static void main(String[] args)
{
try {
Socket soc = new Socket("localhost", 6666);
DataOutputStream d = new DataOutputStream(
soc.getOutputStream());
d.writeUTF("Hello !");
d.flush();
d.close();
soc.close();
}
catch (Exception e) {
System.out.println(e);
}
}
}
URL Class in Java with Examples:
URL known as Uniform Resource Locator is simply a string of text that identifies all the
resources on the Internet, telling us the address of the resource, how to communicate with
it, and retrieve something from it.
Components of a URL
A URL can have many forms. The most general however follows a three-components system
as proposed below:
1. Protocol: HTTP is the protocol here
2. Hostname: Name of the machine on which the resource lives.
3. File Name: The pathname to the file on the machine.
4. Port Number: Port number to which to connect (typically op onal).
URL Class
The URL class is the gateway to any of the resources available on the internet. A Class URL
represents a Uniform Resource Locator, which is a pointer to a “resource” on the World
Wide Web. A resource can point to a simple file or directory, or it can refer to a more
complicated object, such as a query to a database or to a search engine.
Constructors of the URL class
1. URL(String address) throws MalformedURLExcep on: It creates a URL object
from the specified String.
2. URL(String protocol, String host, String file): Creates a URL object from the
specified protocol, host, and file name.
3. URL(String protocol, String host, int port, String file): Creates a URL object from
protocol, host, port, and file name.
4. URL(URL context, String spec): Creates a URL object by parsing the given spec in
the given context.
5. URL(String protocol, String host, int port, String file, URLStreamHandler
handler):
Creates a URL object from the specified protocol, host, port number, file, and
handler.
6. URL(URL context, String spec, URLStreamHandler handler):
Creates a URL by parsing the given spec with the specified handler within a
specified context.
7.
Important Methods used in URL class
Method Ac on Performed
getAuthority() Returns the authority part of URL or null if empty
getDefaultPort() Returns the default port used
Method Ac on Performed
getFile() Returns the file name.
getHost() Return the hostname of the URL in IPv6 format
getPath() Returns the path of the URL, or null if empty
getPort() Returns the port associated with the protocol specified by the URL
getProtocol() Returns the protocol used by the URL
the Returns the query part of URL. A query is a part a er the ‘?’ in
getQuery() the URL. Whenever logic is used to display the result, there would
be a query field in the URL. It is similar to querying a database.
Returns the reference of the URL object. Usually, the reference is
the part marked by a ‘#’ in the URL. You can see the working
getRef()
example by querying anything on Google and seeing the part a er
‘#’
As in any class, toString() returns the string representa on of the
toString()
given URL object.