0% found this document useful (0 votes)
19 views83 pages

CH3 JAVA Networking

Uploaded by

Sohail Nadaf
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)
19 views83 pages

CH3 JAVA Networking

Uploaded by

Sohail Nadaf
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/ 83

NETWORK

1
NETWORKING
 A computer network is combination of two or more
computer systems with each other are known as
computer network.
 so that we can share resources like printer, scanner,
memory.
 Advantage of network Programming:
 Sharing resources like printer, Scanner.
 Centralize software management, Software install on only
one system and used in multiple system.
 Sharing of data due to this reduce redundancy of
application.
 Burden on the developer can be reduced.
 Wastage of memory can be reduced because no need to
install same application on every system.
2
 Time consuming process to develop application is reduced.
JAVA NETWORKING
 Java Networking is a concept of connecting two or more
computing devices together so that we can share
resources.
 Java is practically a synonym for Internet
programming.
 Java provides ability to generate secure, cross-
platform, portable code.
 Java is the premier language for network programming
are the classes defined in the java.net package. They
provide an easy-to-use means by which programmers of
all skill levels can access network resources.
 Java socket programming provides facility to share
data between different computing devices. 3
JAVA NETWORKING TERMINOLOGY

 The widely used java networking terminologies


are given below:
 IP Address

 Protocol

 Socket

 Port Number

 Proxy server

4
IP(INTERNET PROTOCOL) ADDRESS
 A key component of the Internet is the address.
 Every computer on the Internet has one IP address..
 An Internet address is a number that uniquely identifies each
computer on the Net.
 It is a logical address that can be changed.
 Internet addresses:
1. IPv4 (Internet Protocol, version 4): 32-bit,Dotted Decimal Notation
(e,g 192.168.0.1)
1. IPv6 (Internet Protocol, version 6) : 128-bit,hexadecimal notation
(e.g 2002:4559:1FE2::4559:1FE2)

5
 IP address describe a network hierarchy, the name of
an Internet address, called its domain name,
describes a machine’s location in a name space.
For example, www.msbte.com is in the COM
domain (commercial sites); it is called msbte
(after the company name), and www identifies
the server for web requests.
 An Internet domain name is mapped to an IP address
by the Domain Naming Service (DNS). This
enables users to work with domain names, but the
Internet operates on IP addresses.

6
PROTOCOL

 A protocol is a set of rules basically that is


followed for communication.
 For Example:
 IP(InternetProtocol)
 TCP(Transmission Control Protocol)

 UDP(User Datagram Protocol)

 HTTP(HyperText Transfer Protocol)

 FTP(File Transfer Protocol)

 etc

7
 Internet Protocol (IP)
 low-level routing protocol that breaks data into small
packets and sends them to an address across a network.
 It does not guarantee to deliver said packets to the
destination.
 Transmission Control Protocol (TCP)
 Connection Oriented higher-level protocol.
 When two applications want to communicate to each other
reliably, they establish a connection and send data back
and forth over that connection.
 TCP provides a point-to-point channel for applications that
require reliable communications.
 TCP guarantees that data sent from one end of the
connection actually gets to the other end and in the same
order it was sent. Otherwise, an error is reported. 8
 User Datagram Protocol (UDP),
 connectionless, unreliable transport of packets.

 The UDP protocol provides for communication


that is not guaranteed between two applications
on the network.
 UDP is not connection-based like TCP. Rather, it
sends independent packets of data,
called datagrams, from one application to
another. Sending datagrams is much like sending
a letter through the postal service: The order of
delivery is not important and is not guaranteed,
and each message is independent of any other.
 HTTP(Hyper Text Transfer Protocol) is the
protocol that web browsers and servers use to
9
transfer hypertext pages and images
 The Hypertext Transfer Protocol (HTTP), File
Transfer Protocol (FTP), and Telnet are all
examples of applications that require a reliable
communication channel. The order in which the
data is sent and received over the network is
critical to the success of these applications

10
SOCKET
 A socket is an endpoint of a two-way communication link between
two programs running on the 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.
 Socket is a combination of an IP address and a port number.

11
PORTS

 A computer has a single physical connection to the


network. All data destined for a particular computer
arrives through that connection. However, the data may
be intended for different applications running on the
computer.
 A network port is a number that identifies one side of a
connection between two computers. Computers use port
numbers to determine to which process or application a
message should be delivered. As network addresses are
like street address, port numbers are like room
numbers.
 In connection-based communication such as TCP, a
server application binds a socket to a specific port
number. This has the effect of registering the server with 12
the system to receive all data destined for that port.
PROXY SERVER
 Proxy server is a computer that sits between a client
computer and the Internet, and provide indirect
network services to a client.
 An advantage of a proxy server is that its cache can
serve all users. If one or more Internet sites are
frequently requested, these are likely to be in the
proxy's cache, which will improve user response time.
A proxy can also log its interactions, which can be
helpful for troubleshooting.
 How it works:
When a proxy server receives a request for an Internet resource
(such as a Web page), it looks in its local cache of previously
pages. If it finds the page, it returns it to the user without needing
to forward the request to the Internet. If the page is not in the
cache, the proxy server, acting as a client on behalf of the user,
uses one of its own IP addresses to request the page from the
server out on the Internet. When the page is returned, the proxy
server relates it to the original request and forwards it on to the 13
user.
THE NETWORKING CLASSES AND
INTERFACES
 All network classes are available in java.net.*
package

14
 The java.net package’s interfaces are listed
here: The java.net package’s interfaces are
listed here: The java.net package’s
interfaces are listed here:

The java.net package’s interfaces are listed here:

15
InetAddress
 The InetAddress class is used to encapsulate both the
numerical IP address and the domain name for that address.
 You 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.
 InetAddress has following methods:
1. Factory Methods
2. Instance Methods

16
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:


1. static InetAddress getLocalHost( ) throws UnknownHostException
2. static InetAddress getByName(String hostName) throws UnknownHostException
3. static InetAddress[ ] getAllByName(String hostName)throws UnknownHostException

17
 getLocalHost( ) method :returns the InetAddress
object that represents the local host.
 getByName( ) method:returns an InetAddress for a
host name passed to it.
 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.
 getByAddress( ):which takes an IP address and
returns an InetAddress object. unable to resolve the
host name, they throw an UnknownHostException.

18
The following example prints the addresses and names of the local machine
and two well-known Internet web sites:
// Demonstrate InetAddress.
import java.net.*;
class InetAddressTest
{
public static void main(String args[]) throws
UnknownHostException {
InetAddress Address = InetAddress.getLocalHost();
System.out.println(Address);
Address = InetAddress.getByName(“msbte.com");
System.out.println(Address);
InetAddress SW[] =
InetAddress.getAllByName("www.sbionline.com");
for (int i=0; i<SW.length; i++)
System.out.println(SW[i]); 19

}
}
OUTPUT

Sai-PC/192.168.43.237
msbte.com/174.133.117.72
www.sbionline.com/216.157.88.22
www.sbionline.com/64:ff9b:0:0:0:0:d89d:5816

20
URL(UNIFORM RESOURCE LOCATOR)

 URL is the acronym for Uniform Resource Locator.


 It is a reference (an address) to a resource on the
Internet.
 You provide URLs to Web browser so that it can locate
files on the Internet in the same way that you provide
addresses on letters so that the post office can locate
your correspondents.
 The Java URL class represents an URL. It points to a
resource on the World Wide Web.

21
Instance Methods
The InetAddress class has several other methods. Here are some of the more
commonly used methods:

boolean equals(Object other) Returns true if this object has the same
Internet address as other.
byte[ ] getAddress( ) Returns a byte array that represents the
object’s IP address in network byte order.
String getHostAddress( ) Returns a string that represents the host
address associated with the InetAddress
object.
String getHostName( ) Returns a string that represents the host
name associated with the InetAddress
object.
boolean isMulticastAddress( ) Returns true if this address is a multicast
address. Otherwise, it returns false.
String toString( ) Returns a string that lists the host name
and the IP address for
convenience
22
 For example:
http://www.javatpoint.com: 80/java-tutorial/ index.jsp

Protocol Domain Port File Name


Name or Number or Directory
Server Name
Name

A URL contains many information:


 Protocol: In this case, http is the protocol.(http,ftp,telnet etc)
 Server name or IP Address: In this case, www.javatpoint.com is the
server name(Domain Name). The second component is the host name or IP
address of the host to use; this is delimited on the left by double slashes (//)
and on the right by a slash (/) or optionally a colon (:)
 Port Number: It is an optional attribute. 80 is the port number. If port
number is not mentioned in the URL, it returns -1. The third component, the
port number, is an optional parameter, delimited on the left from the host
name by a colon (:) and on the right by a slash (/)
 File Name or directory name: In this case, index.jsp is the file name. 23
 Java’s URL class has several constructors; each can throw a
MalformedURLException.
 URL(String urlSpecifier) throws MalformedURLException
:Creates a URL from the given String.
 URL(String protocolName, String hostName, int port, String path)
throws MalformedURLException
:Creates a URL by putting together the given parts.
 URL(String protocolName, String hostName, String path) throws
MalformedURLException
: Identical to the previous constructor, except that the default port for the
given protocol is used.
 URL(URL urlObj, String urlSpecifier) throws MalformedURLException
:Creates a URL by parsing together the URL and String arguments.

24
Commonly used methods of Java URL class
The java.net.URL class provides many methods.
The important methods of URL class are given below.

Method Description
public String getProtocol() it returns the protocol of the URL.

public String getHost() it returns the host name of the URL.

public String getPort() it returns the Port Number of the URL.

public String getFile() it returns the file name of the URL.

public URLConnection it returns the instance of URL Connection i.e.


openConnection() associated with this URL.
25
// Demonstrate URL.
import java.net.*;
class URLDemo {
public static void main(String args[]) throws MalformedURLException
{
URL url = new URL("http://www.javatpoint.com/java-tutorial");
System.out.println("Protocol: " + url.getProtocol());
System.out.println("Port: " + url.getPort());
System.out.println("Host: " + url.getHost());
System.out.println("File: " + url.getFile());
System.out.println("Ext:" + url.toExternalForm());
}
}
When you run this, you will get the following output:
26
Protocol: http
Port: -1 port is –1; this means that a port was not explicitly set
Host: www.osborne
File: /downloads
Ext:http://www.javatpoint.com/java-tutorial

Notice that the port is –1; this means


that a port was not explicitly set

27
URLConnection
 Given a URL object, you can retrieve the data
associated with it.
 To access the actual bits or content information of a
URL, create a URLConnection object from it, using
its openConnection( ) method, like this:
urlc = url.openConnection()
 openConnection( ) has the following general form:
URLConnection openConnection( ) throws IOException
 It returns a URLConnection object associated with
the invoking URL object. Notice that it may throw an
IOException.

28
URLConnection defines several methods.
 int getContentLength( ) :Returns the size in bytes of the content
associated with the resource. If the length is unavailable, –1 is
returned.
 String getContentType( ) :Returns the type of content found in
the resource. This is the value of the content-type header field.
Returns null if the content type is not available.
 long getDate( ): Returns the time and date of the response
represented in terms of milliseconds since January 1, 1970 GMT.
 long getExpiration( ) :Returns the expiration time and date of
the resource represented in terms of milliseconds since January 1,
1970 GMT. Zero is returned if the expiration date is unavailable.
 String getHeaderField(int idx) :Returns the value of the header
field at index idx. (Header field indexes begin at 0.) Returns null if
the value of idx exceeds the number of fields.
 String getHeaderField(String fieldName) Returns the value of
header field whose name is specified by fieldName. Returns null if
29
the specified name is not found.
 String getHeaderFieldKey(int idx) Returns the header field
key at index idx. (Header field indexes begin at 0.) Returns null if
the value of idx exceeds the number of fields.
 Map<String, List<String>> getHeaderFields( ): Returns a
map that contains all of the header fields and values.
 long getLastModified( ) Returns the time and date,
represented in terms of milliseconds since January 1, 1970 GMT,
of the last modification of the resource. Zero is returned if the
last-modified date is unavailable.
 InputStream getInputStream( ) throws IOException
:Returns an InputStream that is linked to the resource.
This stream can be used to obtain the content of the
resource.

30
// Demonstrate URLConnection.
import java.net.*;
import java.io.*;
import java.util.Date;
class UCDemo
{
public static void main(String args[]) throws Exception {
int c;
URL hp = new URL("http://www.internic.net");
URLConnection hpCon = hp.openConnection();
long d = hpCon.getDate(); // get date
if(d==0)
System.out.println("No date information.");
else
System.out.println("Date: " + new Date(d));
// get content type
System.out.println("Content-Type: " + hpCon.getContentType());
d = hpCon.getExpiration(); // get expiration date
if(d==0)
System.out.println("No expiration information.");
31
else
System.out.println("Expires: " + new Date(d));
d = hpCon.getLastModified(); // get last-modified date
if(d==0)
System.out.println("No last-modified information.");
else
System.out.println("Last-Modified: " + new Date(d));
// get content length
int len = hpCon.getContentLength();
if(len == -1)
System.out.println("Content length unavailable.");
else
System.out.println("Content-Length: " + len);
if(len != 0) {
System.out.println("=== Content ===");
InputStream input = hpCon.getInputStream();
int i = len;
while (((c = input.read()) != -1)) { // && (--i > 0)) {
System.out.print((char) c);
}
input.close();
} else {
System.out.println("No content available.");
}
}
} 32
33
HttpURLConnection
 Java provides a subclass of URLConnection that
provides support for HTTP connections.
 This class is called HttpURLConnection.

 You obtain an HttpURLConnection is same, by


calling openConnection( ) on a URL object, but
you must cast the result to HttpURLConnection.
 Once you have obtained a reference to an
HttpURLConnection object, you can use any of
the methods inherited from URLConnection. You
can also use any of the several methods defined by
HttpURLConnection.

34
 static boolean getFollowRedirects( ) :
Returns true if redirects are automatically followed
and false otherwise. This feature is on by default.
 String getRequestMethod( ):
Returns a string representing how URL requests are
made. The default is GET. Other options, such as
POST, are available.
 int getResponseCode( ) throws IOException
Returns the HTTP response code. –1 is returned if no
response code can be obtained. An IOException is
thrown if the connection fails.
 String getResponseMessage( ) throws IOException
Returns the response message associated with the
response code. Returns null if no message is
available.An IOException is thrown if the connection 35
fails.
 static void setFollowRedirects(boolean how)
If how is true, then redirects are automatically
followed. If how is false, redirects are not
automatically followed. By default, redirects are
automatically followed.
 void setRequestMethod(String how) throws
ProtocolException:
Sets the method by which HTTP requests are
made to that specified by how. The default method
is GET, but other options, such as POST, are
available. If how is invalid, a ProtocolException is
thrown.

36
 The following program demonstrates
HttpURLConnection.
1. It first establishes a connection to
www.google.com.
2. Then it displays the request method, the
response code, and the response message.
3. Finally, it displays the keys and values in the
response header.

37
// Demonstrate HttpURLConnection.
import java.net.*;
import java.io.*;
import java.util.*;
class HttpURLDemo
{
public static void main(String args[]) throws Exception {
URL hp = new URL("http://www.google.com");
HttpURLConnection hpCon = (HttpURLConnection)
hp.openConnection();
// Display request method.
System.out.println("Request method is " +
hpCon.getRequestMethod());
// Display response code.
System.out.println("Response code is " +
38
hpCon.getResponseCode());
// Display response message.
System.out.println("Response Message is " +
hpCon.getResponseMessage());
// Get a list of the header fields and a set
// of the header keys.
Map<String, List<String>> hdrMap =
hpCon.getHeaderFields();
Set<String> hdrField = hdrMap.keySet();
System.out.println("\nHere is the header:");
// Display all header keys and values.
for(String k : hdrField) {
System.out.println("Key: " + k +
" Value: " + hdrMap.get(k));
}
}
}
39
40
JAVA NETWORKING
 TCP
 UDP

41
Clients and servers that communicate via a reliable
channel, such as a TCP socket, have a dedicated
point-to-point channel between themselves.
To communicate, they establish a connection,
transmit the data, and then close the connection.
All data sent over the channel is received in the
same order in which it was sent. This is guaranteed
by the channel.
In contrast, applications that communicate via
datagrams send and receive completely
independent packets of information.
These clients and servers do not have and do not
need a dedicated point-to-point channel.
The delivery of datagrams to their destinations is not
42
guaranteed. Nor is the order of their arrival.
DATAGRAMS
 A datagram is an independent, self-contained
message sent over the network whose arrival, arrival
time, and content are not guaranteed.
 Datagrams are bundles of information passed
between machines.
 Java implements datagrams on top of the UDP
protocol by using two classes:
 DatagramPacket:- object is the data container, It
represents packet that contain data part which is
transferred from one computer to another computer
 DatagramSocket is the mechanism used to send or
receive the DatagramPackets
43
 DatagramSocket defines many methods. Two of the most important
are send( ) and receive( ), which are shown here:
 void send(DatagramPacket packet) throws IOException
The send( ) method sends packet to the port specified by
packet.
 void receive(DatagramPacket packet) throws IOException
The receive( ) method waits for a packet to be received from
the port specified by packet and returns the result
 Other methods give you access to various attributes associated with a
DatagramSocket.
 InetAddress getInetAddress( ): If the socket is connected, then the
address is returned. Otherwise, null is returned.
 int getLocalPort( ) : Returns the number of the local port.
 int getPort( ): Returns the number of the port to which the socket is
connected. It returns –1 if the socket is not connected to a port.
 boolean isBound( ) : Returns true if the socket is bound to an address.
Returns false otherwise.
 boolean isConnected( ) : Returns true if the socket is connected to a
server. Returns false otherwise.
 void setSoTimeout(int millis)throws SocketException :Sets the
time-out period to the number of milliseconds passed in millis.
44
DatagramPacket
 DatagramPacket defines several constructors. Four are
shown here:
1. DatagramPacket(byte data[ ], int size): specifies a
buffer that will receive data and the size of a packet. It
is used for receiving data over a DatagramSocket.
2. DatagramPacket(byte data[ ], int offset, int size):
allows you to specify an offset into the buffer at which
data will be stored.
3. DatagramPacket(byte data[ ], int size, InetAddress
ipAddress, int port): specifies a target address and
port, which are used by a DatagramSocket to
determine where the data in the packet will be sent.
4. DatagramPacket(byte data[ ], int offset, int size,
InetAddress ipAddress, int port): transmits packets
45
beginning at the specified offset into the data
 InetAddress getAddress( ) Returns the address of
the source (for datagrams being received) or
destination (for datagrams being sent).
 byte[ ] getData( ) Returns the byte array of data
contained in the datagram. Mostly used to retrieve
data from the datagram after it has been received.
 int getLength( ) Returns the length of the valid data
contained in the byte array that would be returned
from the
 getData( ) method. This may not equal the length of
the whole byte array.

46
 int getOffset( ) Returns the starting index of the
data.
 int getPort( ) Returns the port number.
 void setAddress(InetAddress ipAddress) Sets the
address to which a packet will be sent.
The address is specified by ipAddress.
 void setData(byte[ ] data) Sets the data to data, the
offset to zero, and the length to number of bytes in
data.
 void setData(byte[ ] data, int idx, int size) Sets
the data to data, the offset to idx, and the length to
size.
 void setLength(int size) Sets the length of the
packet to size.
 void setPort(int port) Sets the port to port.
47
Client(Sender) Program
import java.net.*;
public class Sender{
public static void main(String[] args) throws Exception {
DatagramSocket ds = new DatagramSocket();
String str = "hello world";
InetAddress ia = InetAddress.getByName(“127.0.0.1");
DatagramPacket dp = new DatagramPacket(str.getBytes(),
str.length(), ia, 3000);
ds.send(dp);
ds.close();
}
}

48
Server(Receiver) Program

import java.net.*;
public class Receiver{
public static void main(String[] args) throws Exception {

DatagramSocket ds = new DatagramSocket(3000);


byte[] buf = new byte[1024];

DatagramPacket dp = new DatagramPacket(buf, 1024);


ds.receive(dp);

String strRecv = new String(dp.getData(), 0, dp.getLength());


System.out.println(strRecv);
ds.close();
}
49
}
OUTPUT

50
 Develop a program to send username to server
and server will send “Hello <UserName>” to
client using UDP

51
Client Program
import java.net.*;
public class DSender1{
public static void main(String[] args) throws Exception {
DatagramSocket ds = new DatagramSocket(4000);
InetAddress ia = InetAddress.getLocalHost();
DatagramPacket dp = new
DatagramPacket(ia.getHostName().getBytes(),
ia.getHostName().length(), ia, 3000);
ds.send(dp);
byte[] data1 = new byte[1024];
DatagramPacket packet1 = new
DatagramPacket(data1,data1.length);

// receive the packets


ds.receive(packet1);
String str = new
String(packet1.getData(),0,packet1.getLength());
System.out.println("Hello : "+str); 52

}
Server Side Program
import java.net.*;

public class DReceiver1{


public static void main(String[] args) throws Exception {
InetAddress ia=InetAddress.getLocalHost() ;
DatagramSocket ds = new DatagramSocket(3000);
byte[] buf = new byte[1024];
byte[] data = null;
DatagramPacket dp = new DatagramPacket(buf, 1024);
ds.receive(dp);

String strRecv = new String(dp.getData(), 0, dp.getLength());


System.out.println(strRecv);
DatagramPacket dp1 = new DatagramPacket(strRecv.getBytes(), strRecv.length(),
ia ,4000);
ds.send(dp1);

53
}
}
54
SOCKET PROGRAMMING
 Java Socket programming is used for communication
between computers.
 Java Socket programming can be connection-oriented
or connection-less.
 Socket and ServerSocket classes are used for
connection-oriented socket programming(TCP/IP)
 DatagramSocket and DatagramPacket classes are
used for connection-less socket
programming.(UDP)
 The client in socket programming must know two
information:
1. IP Address of Server, and
2. Port number. 55
CLIENT- SERVER PROGRAMMING USING
TCP/IP 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.

56
 There are two kinds of TCP sockets in Java.
 One is for servers, and the other is for clients.

 The ServerSocket class :This object is used to


establish communication with the clients 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.

57
ServerSocket Class:
Here are three of its constructors:
 ServerSocket(int port ) throws IOException :

Creates server socket on the specified port with a


queue length of 50.
 ServerSocket(int port , int maxQueue ) throws
IOException
Creates a server socket on the specified port with
a maximum queue length of maxQueue.
 ServerSocket(int port , int maxQueue ,
InetAddress localAddress )throws IOException
Creates a server socket on the specified port with
a maximum queue length of maxQueue. On a
multihomed host, localAddress specifies the IP 58
address to which this socket binds.
 ServerSocket has a method called accept( ), which
is a blocking call that will wait for a client to
initiate communications.
 It returns the socket and establish a connection
between server and client.

59
 Each socket has both an OutputStream and an
InputStream.

 The client's OutputStream is connected to


the server's InputStream,

 Client's InputStream is connected to the


server's OutputStream

60
Socket Class :
Here are two constructors used to create client sockets:
 Socket(String hostName , int port ) throws UnknownHostException,
IOException
Creates a socket connected to the named host and
port.
 Socket(InetAddress ipAddress , int port ) throws IOException
Creates a socket using a preexisting InetAddress
object and a port.

61
 Socket defines several instance methods. :
 InetAddress getInetAddress( ): Returns the InetAddress
associated with the Socket object. It returns null if the socket is not
connected.
 int getPort( ) :Returns the remote port to which the invoking Socket
object is connected. It returns 0 if the socket is not connected.
 int getLocalPort( ): Returns the local port to which the invoking
Socket object is bound. It returns –1 if the socket is not bound.
 You can gain access to the input and output streams associated with
a Socket by use of the methods, as shown here. Each can throw an
getInputStream( ) and getOuptutStream( ) IOException if the
socket has been invalidated by a loss of connection.
 InputStream getInputStream( ) throws IOException
:Returns the InputStream associated with the invoking socket.
 OutputStream getOutputStream( ) throws IOException
Returns the OutputStream associated with the invoking
socket.
 Several other methods are available,including:
 connect(),which allows you to specify a new connection ;
 isConnected(), which returns true if the socket is connected to a
server;
 isBound(), which returns true if the socket is bound to an address;
 isClosed( ), which returns true if the socket is closed. 62
THE FOLLOWING STEPS OCCUR WHEN
ESTABLISHING A TCP CONNECTION BETWEEN
TWO COMPUTERS USING SOCKETS

63
 For server program
 Create server socket and begin listening.
 Call accept() method to get new connection from client
socket.
 Create input and output streams for returned socket
for data transfer.
 Conduct the conversation.
 Close client stream and socket when conversion is
over.
 Close server socket.
 For Client program
 create client socket for connection.
 Acquire read and write streams to socket for data
transfer.
 Close stream when connection is over.
 Close client socket. 64
The following are the steps that occur when the connection is established:
1.The ServerSocket object is instantiated by the server with a port number
for communication:
ServerSocket server = new ServerSocket( PORT );
2.The server calls the accept() method of ServerSocket and
waits until the client connects to a given port.
This is called server listening on a given port:
Socket serverclient = server.accept();
3.After this, the client instantiates Socket with the server IP address and port
number:
Socket client = new Socket(server, portid);
4.Then, the constructor of the Socket object tries to connect to the client with
the server on a given port number. On successful connection, CLIENT has
the Socket object through which it can communicate with SERVER.
5.The accept() method of the ServerSocket object on the server side
returns a reference to new Socket, which is connected to the client's socket.
65
6.Once connected, the communication occurs through Java I/O streams;
each socket has both OutputStream and InputStream.
The server's java.io.OutputStream communicates with the
client's InputStream string and vice versa.
As said earlier, in TCP, data flows in both directions at the same time:
DataInputStream ips = new
DataInputStream(client.getInputStream());
DataOutputStream ops = new
DataOutputStream(client.getOutputStream());
Client receive: String line = is.readLine();
Client send: os.writeUTF(“Hello World!n”);
7.Close the socket when the data exchange is complete:
client.close();

66
CLIENT TO SERVER COMMUNICATION (ONE-
WAY)
Client Side Program
import java.net.*;
import java.io.*;
public class client
{
public static void main(String args[]) throws Exception
{
Socket sock = new Socket("127.0.0.1", 5000);
String msg = "HELLO, Server";
OutputStream os = sock.getOutputStream();
DataOutputStream dos = new DataOutputStream(os);
dos.writeUTF(msg);
dos.close();
os.close();
67
sock.close();
}
Sever Side Program

import java.net.*;
import java.io.*;
public class server
{
public static void main(String args[]) throws Exception
{
ServerSocket sersock = new ServerSocket(5000);
System.out.println("server is ready"); // message to know the server is
running
Socket sock = sersock.accept();
InputStream is = sock.getInputStream();
DataInputStream dis = new DataInputStream(is);
String msg1 = dis.readUTF();
System.out.println(msg1);
68
dis .close(); is.close(); sock.close(); sersock.close();
69
 Chat Program two way communication Java

70
import java.net.*;
import java.io.*;
public class client1
{
public static void main(String args[]){
try
{
Socket s=new Socket("127.0.0.1",3456);
InputStream is=s.getInputStream();
OutputStream os=s.getOutputStream();
DataInputStream dis=new DataInputStream(is);
DataOutputStream dos=new DataOutputStream(os);
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
while(true)
{
System.out.println("Enter Data: ");
String l=br.readLine();
dos.writeUTF(l);
String str=dis.readUTF();
System.out.println(str);
71
}}
catch(Exception e)
{}}}
import java.net.*;
import java.io.*;
public class server1
{
public static void main(String args[]){
try
{
ServerSocket ss=new ServerSocket(3456);
Socket s1=ss.accept();
System.out.println("Got Client");
InputStream is=s1.getInputStream();
OutputStream os=s1.getOutputStream();
DataInputStream dis=new DataInputStream(is);
DataOutputStream dos=new DataOutputStream(os);
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
while(true)
{
String line=dis.readUTF();
System.out.println("Enter Data");
String str=br.readLine();
dos.writeUTF(str); 72
}}
catch(Exception e)
73
Develop a program to send number through client
to server and server will send the message to client
that number is prime or not.

74
Client side
import java.net.*;
import java.io.*;
public class client3
{
public static void main(String args[]){
try
{
Socket s=new Socket("127.0.0.1",3458);
InputStream is=s.getInputStream();
OutputStream os=s.getOutputStream();
DataInputStream dis=new DataInputStream(is);
DataOutputStream dos=new DataOutputStream(os);
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
while(true)
{
System.out.println("Enter Number: ");
String l=br.readLine();
dos.writeUTF(l);
String str=dis.readUTF();
System.out.println(str);
75
}}
catch(Exception e)
{}}}
Server side

import java.net.*;
import java.io.*;6rx
public class server3
{
public static void main(String args[]){
try
{
ServerSocket ss=new ServerSocket(3458);
Socket s1=ss.accept();
System.out.println("Got Client");
InputStream is=s1.getInputStream();
OutputStream os=s1.getOutputStream();
DataInputStream dis=new DataInputStream(is);
DataOutputStream dos=new DataOutputStream(os);
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
while(true)
{ 76
String line=dis.readUTF();
int result = Integer.parseInt(line);
int i,m=0,flag=0;
m=result/2;
if(result==0||result==1)
{
String str="Number is not Prime";
dos.writeUTF(str);;
}
else
{
for(i=2;i<=m;i++)
{
if(result%i==0)
{
String str=" Number is Not Prime";
dos.writeUTF(str);
flag=1;
break;
}
}
if(flag==0) { String str="Number is Prime";
dos.writeUTF(str); }
}//end of else 77
}}
catch(Exception e)
{}}}
78
 Develop a program to send a password through
client to server and server will send message to
client that password is valid or invalid

79
import java.io.*;
import java.net.*;
public class client4
{
public static void main(String args[]){
try
{
Socket s=new Socket("127.0.0.1",4444);
InputStream is=s.getInputStream();
OutputStream os=s.getOutputStream();
DataInputStream dis=new DataInputStream(is);
DataOutputStream dos=new DataOutputStream(os);
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
System.out.println("Enter Password: ");
String passwd=br.readLine();
dos.writeUTF(passwd);
String str=dis.readUTF();
System.out.println(str);
}
catch(Exception e)
80
{}}}
import java.io.*;
import java.net.*;
public class server4 {
public static void main(String args[]){
try
{
ServerSocket ss=new ServerSocket(4444);
Socket s1=ss.accept();
System.out.println("Connected to client....");
InputStream is=s1.getInputStream();
OutputStream os=s1.getOutputStream();
DataInputStream dis=new DataInputStream(is);
DataOutputStream dos=new DataOutputStream(os);
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String pass1=dis.readUTF();
if(pass1.equals("Java1234"))
{
String str="Password is valid";
dos.writeUTF(str);
}
else
{ String str="Password is invalid"; 81
dos.writeUTF(str);;
} } catch(Exception e){}}}
82
83

You might also like