OBJECT ORIENTED
PROGRAMMING
Networking with Java
Prepared by
Dr. Abinash Tripathy
School of Computer Application
KIIT Deemed to be University, Bhubaneswar
Networking with Java
• Java is practically a synonym for Internet programming. There are a number of
reasons for this, not the least of which is its ability to generate secure, cross-
platform, portable code.
• However, one of the most important reasons that Java is the premier language for
network programming are the classes defined in the [Link] package.
• At the core of Java’s networking support is the concept of a socket. A socket
identifies an endpoint in a network.
• Sockets are at the foundation of modern networking because a socket allows a
single computer to serve many different clients at once, as well as to serve many
different types of information.
• This is accomplished through the use of a port, which is a numbered socket on a
particular machine.
• A server process is said to "listen" to a port until a client connects to it. A server is allowed to accept multiple
clients connected to the same port number, although each session is unique.
• To manage multiple client connections, a server process must be multithreaded or have some other means of
multiplexing the simultaneous I/O.
• Socket communication takes place via a protocol. Internet Protocol (IP) is a low-level
routing protocol that breaks data into small packets and sends them to an address across a
network, which does not guarantee to deliver said packets to the destination.
• Transmission Control Protocol (TCP) is a higher-level protocol that manages to robustly string together these
packets, sorting and retransmitting them as necessary to reliably transmit data.
• A third protocol, User Datagram Protocol (UDP), sits next to TCP and can be used directly to support fast,
connectionless, unreliable transport of packets.
• A key component of the Internet is the address. Every computer on the Internet has one. An Internet address is
a number that uniquely identifies each computer on the Net.
• Originally, all Internet addresses consisted of 32-bit values, organized as four 8-bit values. This address type
was specified by IPv4 (Internet Protocol, version 4).
• However, a new addressing scheme, called IPv6 (Internet Protocol, version 6) has come into play. IPv6 uses a
128-bit value to represent an address, organized into eight 16-bit chunks.
InetAddress Class
• The InetAddress class is used to encapsulate both the numerical IP
address and the domain name for that address.
• We interact with this class by using the name of an IP host, which is
more convenient and understandable than its IP address.
• The InetAddress class hides the number inside.
• InetAddress can handle both IPv4 and IPv6 addresses
Factory Methods
• The InetAddress class has no visible constructors. To create an InetAddress object, you have to use one of the
available factory methods.
• Factory methods are merely a convention whereby static methods in a class return an instance of that class.
• Three commonly used InetAddress factory methods are shown here:
• static InetAddress getLocalHost( ) throws UnknownHostException
• static InetAddress getByName(String hostName) throws UnknownHostException
• static InetAddress[ ] getAllByName(String hostName) throws UnknownHostException
• The getLocalHost( ) method simply returns the InetAddress object that represents the local host.
• The getByName( ) method returns an InetAddress for a host name passed to it. If these methods are unable to
resolve the host name, they throw an UnknownHostException.
• The getAllByName( ) factory method returns an array of InetAddresses that represent all of the addresses that
a particular name resolves to. It will also throw an UnknownHostException if it can’t resolve the name to at
least one address.
// Demonstrate InetAddress.
import [Link].*;
class InetAddressTest
{
public static void main(String args[]) throws UnknownHostException
{
InetAddress Address = [Link]();
[Link](Address);
Address = [Link]("[Link]");
[Link](Address);
InetAddress SW[] = [Link]("[Link]");
for (int i=0; i<[Link]; i++)
[Link](SW[i]);
}
}
C:\java\lab>javac [Link]
C:\java\lab>java InetAddressTest
Abhyudaya/[Link]
[Link]/[Link]
[Link]/[Link]
TCP/IP Client Sockets
• TCP/IP sockets are used to implement reliable, bidirectional, persistent, point-to-
point, stream-based connections between hosts on the Internet.
• A socket can be used to connect Java’s I/O system to other programs that may
reside either on the local machine or on any other machine on the Internet.
• There are two kinds of TCP sockets in Java. One is for servers, and the other is for
clients.
• The ServerSocket class is designed to be a "listener," which waits for clients to
connect before doing anything. Thus, ServerSocket is for servers.
• The Socket class is for clients. It is designed to connect to server sockets and
initiate protocol exchanges. Because client sockets are the most commonly used
by Java applications, they are examined here.
• The creation of a Socket object implicitly establishes a connection between the client and server.
• Here are two constructors used to create client sockets:
• Socket(String hostName, int port) throws UnknownHostException, IOException: Create a socket
connected to the named host and port
• Socket(InetAddress ipAddress, int port) throws IOException : create a socket using a preexisting
InetAddress object and port.
• You can gain access to the input and output streams associated with a Socket by use of the getInputStream( )
and getOuptutStream( ) methods. Each can throw an IOException if the socket has been invalidated by a loss
of connection.
• InputStream getInputStream( ) throws IOException : Return to InputStream associated with the
invoking socket.
• OutputStream getOutputStream( ) throws IOException : Return to OutputStream associated with
the invoking socket.
• Several other methods are available as follows:
• connect() : which allow us to specify a new connection
• isConnected(): which return true if socket is connected to a server.
• isBound(): which returns true if the socket is bound to an address
• isClosed: which returns true if socket is closed.
• Here is how the program works.
• First, a Socket is constructed that specifies the host name "[Link]" and the port number
43.
• [Link] is the InterNIC web site that handles whois requests. Port 43 is the whois port.
• Next, both input and output streams are opened on the socket.
• Then, a string is constructed that contains the name of the web site you want to obtain information
about.
• In this case, if no web site is specified on the command line, then "[Link]" is used.
• The string is converted into a byte array and then sent out of the socket.
• The response is read by inputting from the socket, and the results are displayed.
• Finally, the socket is closed, which also closes the I/O streams.
// Demonstrate Sockets.
import [Link].*;
import [Link].*;
class Whois
{
public static void main(String args[]) throws Exception
{
int c;
Socket s = new Socket("[Link]", 43);
InputStream in = [Link]();
OutputStream out = [Link]();
String str = ([Link] == 0 ? "[Link]" : args[0]) + "\n";
byte buf[] = [Link]();
[Link](buf); C:\java\lab>javac [Link]
while ((c = [Link]()) != -1) C:\java\lab>java Whois
[Link]((char) c); Domain Name: [Link]
Registry Domain ID: 479181747_DOMAIN_COM-VRSN
[Link]();
Registrar WHOIS Server: [Link]
}
} Registrar URL: [Link]
Updated Date: 2022-06-05T05:15:14Z
Creation Date: 2006-06-09T16:44:39Z
Registry Expiry Date: 2023-06-09T16:44:39Z
Registrar: CSC Corporate Domains, Inc.
Socket class
• A socket is simply an endpoint for communications between the machines. The
Socket class can be used to create a socket.
Methods of Socket Class
1. public InputStream getInputStream() : return the input stream connected with the socket
2. public OutputStream getOutputStream() : return the output stream connected with socket
3. public synchronized void close(): closes the socket.
Server Socket Class
• The ServerSocket class can be used to create a server socket. This
object is used to establish communication with the clients.
Methods of Server Socket Class
1. public Socket accept () : return the socket and establish a connection
between server and client.
2. public synchronized void close () : close the server socket
Example of Java Socket Programming
Creating Server:
• To create the server application, we need to create the instance of ServerSocket class.
• Here, we are using 6666 port number for the communication between the client and server.
• You may also choose any other port number. The accept() method waits for the client.
• If clients connects with the given port number, it returns an instance of Socket.
ServerSocket ss = new ServerSocket(6666);
Socket s = ss. accept(); // establishes connection and waits for the client
Creating Client:
• To create the client application, we need to create the instance of Socket class.
• Here, we need to pass the IP address or hostname of the Server and a port number.
• Here, we are using "localhost" because our server is running on same system.
Socket s=new Socket("localhost",6666);
import [Link].*;
import [Link].*;
public class MyServer
{
public static void main(String[] args)
{
try
{
ServerSocket ss=new ServerSocket(6666);
Socket s=[Link]();//establishes connection
DataInputStream dis=new DataInputStream([Link]());
String str=(String)[Link](); //Unicode Translation Format
[Link]("message= "+str);
[Link]();
}
catch(Exception e)
{ C:\java\lab>javac [Link]
[Link](e);
} C:\java\lab>java MyServer
}
}
import [Link].*;
import [Link].*;
public class MyClient
{
public static void main(String[] args)
{
try
{
Socket s=new Socket("localhost",6666);
DataOutputStream dout=new DataOutputStream([Link]());
[Link]("Hello Server");
[Link]();
[Link]();
[Link]();
}
catch(Exception e) C:\java\lab>javac [Link]
{
[Link](e); C:\java\lab>java MyClient
}
}
}
Example of Java Socket Programming (Read-Write both side)
• In this example, client will write first to the server then server will
receive and print the text. Then server will write to the client and
client will receive and print the text. The step goes on.
//Server side program
import [Link].*;
import [Link].*;
class MyServer1{
public static void main(String args[])throws Exception{
ServerSocket ss=new ServerSocket(3333);
Socket s=[Link]();
DataInputStream din=new DataInputStream([Link]());
DataOutputStream dout=new DataOutputStream([Link]());
BufferedReader br=new BufferedReader(new InputStreamReader([Link]));
String str="",str2="";
while(){
str=[Link]();
[Link]("client says: "+str);
str2=[Link]();
[Link](str2);
[Link]();
}
[Link]();
[Link]();
[Link]();
}}
//client side program
import [Link].*;
import [Link].*;
class MyClient1{
public static void main(String args[])throws Exception{
Socket s=new Socket("localhost",3333);
DataInputStream din=new DataInputStream([Link]());
DataOutputStream dout=new DataOutputStream([Link]());
BufferedReader br=new BufferedReader(new InputStreamReader([Link]));
String str="",str2="";
while(){
str=[Link]();
[Link](str);
[Link]();
str2=[Link]();
[Link]("Server says: "+str2);
}
[Link]();
[Link]();
}}
How to run
• Compile the java program ([Link])
• Run the program
• Open another command prompt
• Compile the client side java program ([Link])
• Run the program, it ask for text message
• After giving text message, it is shown in server window
• Similar process happen at server side.
• Communication is going on until both write the message stop