Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Networking in Java

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 57

Networking in

Java

1
Objectives:

 Learn about the basic java classes


(java.net package) that supports
Socket programming, namely:
 Basic network concepts
 InetAddress
 Socket
 ServerSocket
 DatagramSocket
 DatagramPacket
 MulticastSocket
2
Basic network concepts

 A computer network is an
interconnected collection of
autonomous computers.

3
What a Network Includes

 A network includes:
 Special purpose hardware
devices that:
 Interconnect transmission media
 Control transmission of data
 Run protocol software

 Protocol software that:


 Encodes and formats data
 Detects and corrects problems encountered during
transmission

4
Addressing and Routing

 Address: byte-string that identifies a node


 usually unique
 Routing: process of forwarding messages
to the destination node based on its
address
 Types of addresses
 unicast: node-specific
 broadcast: all nodes on the network
 multicast: some subset of nodes on the
network
5
What is protocol?

 A protocol is a set of rules of communication.


Protocols are the building blocks of a network
architecture.
 Each protocol object has two different interfaces:
 service interface: operations on this protocol
 peer-to-peer interface: messages exchanged with
peer
 Term “protocol” is overloaded
 specification of peer-to-peer interface
 module that implements this interface

6
Conti …

7
Two types of Communication

 Connection-oriented
 Setup the link before communication.
 Similar to the phone call. We need the phone
number and receiver.
 Example:- TCP (Transmission Control Protocol)
 Connectionless
 No link needed to be set up before
communication.
 Similar to send a letter. We need the address and
receiver.
 Example:- UDP (User Datagram Protocol)
8
TCP/IP

 A protocol is a set of rules that determine


how things communicate with each other
 The software which manages Internet
communication follows a suite of protocols
called TCP/IP
 The Internet Protocol (IP) determines the
format of the information as it is
transferred
 The Transmission Control Protocol (TCP)
dictates how messages are reassembled
and handles lost information
9
IP and Internet Addresses

 Each computer on the Internet has a unique


IP address, such as:
 130.136.1.110
 Most computers also have a unique Internet
name, which also is referred to as an Internet
address:
 www.cs.unibo.it
 The first part indicates a particular computer
(www)
 The rest is the domain name, indicating the
organization (cs.unibo.it)
10
TCP(Transmission Control
Protocol:)

 It’s a reliable connection-oriented


protocol
 Reliability is achieved using packets
indexing and generating “ack”
messages for each received packet
 Creating a connection is an
asymmetrical process; once the
connection is established the protocol
becomes symmetric
 Ports are used to initiate a connection 11
Connection Sequence

12
TCP Standard Ports

 Below 1024, assigned by the IANA

21 FTP

23 Telnet

80 HTTP
11
POP3
0
11
NNTP
9

13
TCP Protocol

14
15
Network Programming

 Mechanisms by which software running on two or


more computational devices can exchange
messages

 A network allows arbitrary applications to


communicate.

 Network facilities are accessed through an


Application Programming Interface (API);
e.g., a Service Interface.

 Java is a network centric programming language


16
Cont…

 The network is the soul of Java.

 Most of what is interesting about Java


centers around the potential for
dynamic, networked applications.

 As Java's networking APIs have matured,


Java has also become the language of
choice for implementing client-server
applications and services.
17
Cont…

 java.net package, which contains the


fundamental classes for
communications and working with
network

18
Network Programming in java

1. The InetAddress class:


 The java.net.InetAddress class is used to
represent an IP address as an object. It
is also used to resolve from host name to
IP address (via the DNS) and vice versa.

 No Constructors, instead, factory


methods are provided.
 The following are some of the methods
of the InetAddress class.
19
Static InetAddress Takes a hostname and returns
getByName(String InetAddress object representing its
host) IP address.
Static InetAddress[] Takes a hostname and returns an
getAllByName(Strin array of InetAddress objects
g host) representing its IP addresses.
static InetAddress Returns an InetAddress object
getLocalHost() representing the IP address of the
local host
String Returns IP address string of this
getHostAddress() InetAddress object
string Returns the hostname of this
getHostName() InetAddress object.
boolean Checks if the InetAddress is a
isLoopbackAddress() loopback address.
boolean Checks if the InetAddress is an IP
isMulticastAddress() multicast address.
String toString() Converts this InetAddress 20
to a
String.
Cont…

Example 1: IP Address Resolver.


 The following example first prints the
Address of the current machine and
then in a loop reads a host or an
address from a user and resolving it.

21
TCP
Connections
in Java

22
TCP Protocol
 There is a server process P2 and a client process P1.
P1 and P2 establish a communication line between
them using TCP sockets. P1 reads a message from
the user and places that message on the socket.

 The message reaches socket in P2. P2 reads the


message from the socket and displays it. Also P2
sends back the same message to P1 by placing it on
the socket. P1 reads the message from the socket
and displays it to the user.
 The following are the system calls that are to be
executed for connection oriented communication
between two processe
23
Cont…

24
Cont…

 Usually computers running on the Internet


communicate to each other using either
the Transmission Control Protocol (TCP) or
the User Datagram Protocol (UDP):

 When you write Java programs that


communicate over the network, you are
programming at the application layer
25
Cont…

 When two applications want to communicate to


each other reliably, they establish a connection
and send data back and forth over that
connection.
 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.
 TCP provides a point-to-point channel for
applications that require reliable communications.
 TCP (Transmission Control Protocol) is a
connection-based protocol that provides a
reliable flow of data between two computers.
26
TCP Sockets (Stream Sockets)

 Java provides two classes for creating TCP sockets,


namey, Socket and ServerSocket.

The java.net.Socket class:


 This class is used by clients to make a connection with
a server
 A socket is one endpoint of a two-way communication
link between two programs running on the network.
 Normally, a server runs on a specific computer and
has a socket that is bound to a specific port number.
The server just waits, listening to the socket for a
client to make a connection request.
27
Cont…

 On the client-side: The client knows


the hostname of the machine on
which the server is running and the
port number to which the server is
connected. To make a connection
request, the client tries to rendezvous
with the server on the server's
machine and port.

28
Cont…

 If everything goes well, the server accepts the


connection. Upon acceptance, the server gets
a new socket bound to a different port.
 It needs a new socket (and consequently a
different port number) so that it can continue
to listen to the original socket for connection
requests while tending to the needs of the
connected client.
 On the client side, if the connection is
accepted, a socket is successfully created and
the client can use the socket to communicate
with the server.
29
Cont…

 To do is you should perform five basic steps:


 Open a socket.
 Open an input stream and output stream to the
socket.
 Read from and write to the stream according to
the server's protocol.
 Close the streams.
 Close the socket.
30
Cont…

Socket constructors are:


 Socket(String hostname, int port)
 Throws IOException, UnknownHostException
 Connects to a server socket at the
provided address (host) on the
provided port
31
Cont…

 Socket(InetAddress addr, int port)


 Socket(String hostname, int port,
InetAddress localAddr, int localPort)
 Socket(InetAddress addr, int port,
InetAddress localAddr, int localPort)

32
Cont…

Creating socket
 Socket client = new
Socket(“www.microsoft.com", 80);
 Note that the Socket constructor attempts to
connect to the remote server - no separate
connect() method is provided.
 Data is sent and received with output and input
streams.
 The Socket class has the following methods,
that retruns InputStream and the
OutputStream for reading and writing to the
socket
33
Cont…

 public InputStream getInputStream()


 Throws IOException
 Returns the input stream from the socket
 public OutputStream getOutputStream()
 Throws IOException
 Returns the output stream from the
socket
 There's also a method to close a socket:
 public synchronized void close()
34
Cont…

 The following methods are also


provided to set socket options:
 void setReceiveBufferSize()
 void setSendBufferSize()
 void setTcpNoDelay()
 void setSoTimeout()

35
The java.net.ServerSocket
class

 The ServerSocket class is used to


by server to accept client
connections
 The constructors for the class are:
 public ServerSocket(int port)
 public ServerSocket(int port, int
backlog)
 public ServerSocket(int port, int
backlog, InetAddress
networkInterface) 36
Cont…
 Creating a ServerSocket
 ServerSocket server = new ServerSocket(80, 50);
 Note: a closed ServerSocket cannot be reopened
 ServerSocket objects use their accept() method to
connect to a client

 public Socket accept()


 accept() method returns a Socket object, and its
getInputStream() and getOutputStream() methods
provide streams for reading and writing to the client.

37
Cont…

try {
serverSocket = new
ServerSocket(4444);
} catch (IOException e) {
System.out.println("Could not listen on
port: 4444"); System.exit(-1);
}
 If the server successfully connects to its
port, then the ServerSocket object is
successfully created and the server continues to
the next step - accepting a connection from a
client:
38
Cont…

Socket clientSocket = null;


try {
clientSocket = serverSocket.accept();
} catch (IOException e) {// accept failed}
 The accept method waits until a client starts up
and requests a connection on the host and port
of this server.

 When a connection is requested and successfully


established, the accept method returns a new
Socket object which is bound to a new port.
39
Cont…

 After the server successfully establishes a


connection with a client, it communicates
with the client:
PrintWriter out =
new
PrintWriter( clientSocket.getOutputStream(),
true);
BufferedReader in =
new BufferedReader( new
InputStreamReader( clientSocket.getInputSt
ream()));
40
Cont…

 Server can service clients simultaneously


through the use of threads - one thread per
each client connection. The basic flow of
logic in such a server is this:
while (true) {
accept a connection ;
create a thread to deal with the client ;
}
 Note: There are no getInputStream() or
getOutputStream() methods for
ServerSocket
41
Using TCP in Java (Sockets)

Sending/receiving data on TCP from a


client:
– Create a socket.
– Obtain Input/Output stream from
socket.
– Build stream chain as desired.
– Write/Read from stream chain.
– Close stream and socket.
42
Cont…

Sending/receiving data on TCP from a


server:
– Create socket.
– Wait for connections.
– Upon connection create a new socket.
– Obtain Input/Output streams from
socket.
– Build stream chain.
– Write/Read from stream chain and 43

close everything.
Connectionles
s
communicatio
n
UDP

44
introduction

 The UDP protocol provides for communication


that is not guaranteed between two
applications on the network.

 UDP sends independent packets of data, called


datagrams, from one application to another.

 Sometimes reliability provided by TCP is not


necessary and you can use UDP which doesn’t
have overhead related to establishing
connection.
45
UDP Protocol

 There is a server process p2 and a client


process p1. p1 and p2 communicate with
each other using datagram sockets based on
User Datagram Protocol (UDP), in which there
is no connection between the 2 processes.
 P1 reads a message from the user and places
that message on the socket. It reaches
socket of p2. p2 reads the message and
displays it. Also p2 sends back the same
message to p1 by placing it on the socket. P1
reads the message from the socket and
displays it to the user.
46
Cont…

 The following are the system calls that are to


be executed for connectionless
communication between 2 processes that
uses UDP protocol.

47
UDP Sockets (Datagram
Sockets)

 Java provides two classes for creating UDP


Sockets:
 DatagramPacket class, used to represent the
data for sending and receiving.
 DatagramSocket class for creating a socket
used to send and receive DatagramPackets.

 The java.net.DatagramPacket class:


 Constructor for receiving:
 public DatagramPacket(byte[] data, int length)

48
Cont…

 Constructor for sending :


public DatagramPacket(byte[] data, int length,
InetAddress addr, int port)
 Some methods provided by the
DatagramPacket class are:
 public synchronized void
setAddress(InetAddress addr)
 public synchronized void setPort(int port)
 public synchronized void setData(byte data[])
 public synchronized void setLength(int length)

49
Cont…

The java.net.DatagramSocket
class:
 Constructor for sending:
 public DatagramSocket()

 Constructor for receiving :


 public DatagramSocket(int port)
 public DatagramSocket(int port,
InetAddress addr) 50
cont…

 Sending UDP Datagrams involves the


following steps:
1. Convert the data into byte array.
2. Create a DatagramPacket using
the array
3. Create a DatagramSocket using
the packet and then call send()
method

51
Cont…

 Receiving UDP Datagrams involves the


following steps:
1. Construct a DatagramSocket object on the
port on which you want to listen
2. Pass an empty DatagramPacket object to
the DatagramSocket's receive() method
 public synchronized void
receive(DatagramPacket dp)
 The calling thread blocks until a datagram is
received
 dp is filled with the data from that datagram
52
Cont…

Notes:
 After receiving, use the getPort() and
getAddress() on the received packet
to know where the packet came from.
Also use getData() to retrieve the data,
and getLength() to see how many
bytes were in the data
 The received packet could be truncated
to fit the buffer
53
Using UDP in Java
(Datagrams)
Same mechanism for client AND server.
• To RECEIVE data:
– Create a DatagramSocket with port.
– Create a DatagramPacket.
– Receive the data through Socket into
the Packet.

54
Cont…

• To SEND data:
– Create DatagramSocket with address
and port.
– Create DatagramPacket.
– Fill Packet with Data.
– Send Packet through Socket.

55
Cont…

 Example 5: The following


examples show how to create a
UdpEchoServer and the
corresponding UdpEchoClient.

56
Multicast Sockets

 Multicasting is achieved in Java using the same


DatagramPacket class used for normal
Datagrams. This is used together with the
MulticastSocket class.

 The MulticastSocket class is a subclass of the


DatagramSocket class, with the following
methods for joining and leaving a multicast group
added.
 void joinGroup(InetAddress mcastaddr)
 void leaveGroup(InetAddress mcastaddr)
 void setTimeToLive(int ttl)
57

You might also like