Top Banner
Networking Shravan Upadhayay
30

Networking in java

May 17, 2015

Download

Education

Java.net package provides support for networking.
What makes Java a good language for networking are the classes defined in the java.net package.
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Networking in java

Networking

Shravan Upadhayay

Page 2: Networking in java

Shravan Upadhayay

Introduction

Java.net package provides support for networking.

What makes Java a good language for networking are the classes defined in the java.net package.

Page 3: Networking in java

Shravan Upadhayay

Concept of Networking

Page 4: Networking in java

Shravan Upadhayay

Sockets

Socket is the name given , in one particular programming model, to the end points of a communication link between processes.

When processes communicate over a network, Java Technology uses streams model.

Page 5: Networking in java

Shravan Upadhayay

Sockets

Sockets: Sockets hold two streams: an input

stream and an output stream. Each end of the socket has a pair of

streams.

Page 6: Networking in java

Shravan Upadhayay

Socket A process send data to another process

through a network by writing to the output stream associated with the Socket.

A process reads data written by another process by reading from the input stream associated with the Socket.

Page 7: Networking in java

Shravan Upadhayay

Setting Up the Connection To setup the network connection, one

machine must run a program that is waiting for a connection, and a second machine must try to reach the first.

Set up of a network connection is similar to a telephone system: One end must dial the other end, which must be listening.

Page 8: Networking in java

Shravan Upadhayay

Networking

Page 9: Networking in java

Shravan Upadhayay

Addressing the Connection

When you make a network connection, you need to know the address or the name of the remote machine.

In addition, a network connection, requires a port number, which you can think of as a telephone extension number.

Page 10: Networking in java

Shravan Upadhayay

Port Numbers Port numbers in TCP/IP systems are

16-bit numbers and the values range from 0-65535. Port numbers below 1024 are reserved

for predefined services. Client port numbers are allocated by the

host OS to something not in use, while server port numbers are specified by the programmer, and are used to identify a particular service.

Page 11: Networking in java

Shravan Upadhayay

Both client and server must agree in advance on which port to use.

If the port numbers used by the two parts of the system do not agree, communication does not occur.

Page 12: Networking in java

Shravan Upadhayay

Server

A server is anything that has some resource that can be shared. There are compute servers, which

provide computing power; print servers, which manage a collection

of printers; disk servers, which provide networked

disk space; and web servers, which store web pages.

Page 13: Networking in java

Shravan Upadhayay

Client

A client is simply any other entity that wants to gain access to a particular server.

Page 14: Networking in java

Shravan Upadhayay

The notion of a socket allows a single computer to serve many different clients at once, as well as serving many different types of information.

This feat is managed by the introduction 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.

Page 15: Networking in java

Shravan Upadhayay

Local Host Info// Demonstrate InetAddress.import java.net.*;class InetAddressTest{public static void main(String args[]) throwsUnknownHostException{InetAddress Address = InetAddress.getLocalHost();System.out.println(Address.getHostName());System.out.println(Address.getHostAddress());}}

Page 16: Networking in java

Shravan Upadhayay

TCP/IP 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.

Page 17: Networking in java

Shravan Upadhayay

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.

The Socket class is designed to connect to server sockets and initiate protocol exchanges.

Page 18: Networking in java

Shravan Upadhayay

The creation of a Socket object implicitly establishes a connection between the client and server.

There are no methods or constructors that explicitly expose the details of establishing that connection.

Page 19: Networking in java

Shravan Upadhayay

Here are two constructors used to create client sockets: Socket(String hostName, int port) Creates a socket connecting the local host to the

named host and port; can throw an UnknownHostException or an IOException.

Socket(InetAddress ipAddress, int port) Creates a socket using a preexisting

InetAddress object and a port; can throw an IOException.

Page 20: Networking in java

Shravan Upadhayay

A socket can be examined at any time for the address and port information associated with it, by use of the following methods: InetAddress getInetAddress( )

Returns the InetAddress associated with the Socket object. int getPort( )

Returns the remote port to which this Socket object is connected. int getLocalPort( )

Returns the local port to which this Socket object is connected.

Page 21: Networking in java

Shravan Upadhayay

Once the Socket object has been created, it can also be examined to gain access to the input and output streams associated with it.

Each of these methods can throw an IOException if the sockets have been invalidated by a loss of connection on the Net.

These streams are used exactly like the I/O streams receive data.

InputStream getInputStream( ) Returns the InputStream

Page 22: Networking in java

Shravan Upadhayay

InputStream getInputStream( ) Returns the InputStream associated

with the invoking socket. OutputStream getOutputStream() Returns the OutputStream

associated with the invoking socket. void close() Closes both the InputStream and

OutputStream.

Page 23: Networking in java

Shravan Upadhayay

Socket functional calls socket (): Create a socket bind(): bind a socket to a local IP address and port # listen(): passively waiting for connections connect(): initiating connection to another socket accept(): accept a new connection Write(): write data to a socket Read(): read data from a socket close(): close a socket (tear down the connection)

Page 24: Networking in java

Shravan Upadhayay

Socket-programming using TCPTCP service: reliable byte stream transfer

process

TCP withbuffers,

variables

socket

controlled byapplicationdeveloper

controlled byoperating

system

process

TCP withbuffers,

variables

socket

internet

clientserversocket( )

bind( )connect( )

socket( )bind( )listen( )

accept( )send( )

recv( )

close( ) close( )

recv( )send( )

TCP conn. request

TCP ACK

Page 25: Networking in java

Shravan Upadhayay

Socket programming with TCP

Example client-server app: client reads line from

standard input (inFromUser stream) , sends to server via socket (outToServer stream)

server reads line from socket

server converts line to uppercase, sends back to client

client reads, prints modified line from socket (inFromServer stream)

outT

oSer

ver

to network from network

inFr

omS

erve

r

inFr

omU

ser

keyboard monitor

Process

clientSocket

inputstream

inputstream

outputstream

TCPsocket

Input stream: sequence of bytesinto process

output stream: sequence of bytes out of process

Clientprocess

client TCP socket

Page 26: Networking in java

Shravan Upadhayay

Client/server socket interaction: TCP

wait for incomingconnection requestconnectionSocket =welcomeSocket.accept()

create socket,port=x, forincoming request:welcomeSocket =

ServerSocket()

create socket,connect to hostid, port=xclientSocket =

Socket()

closeconnectionSocket

read reply fromclientSocket

closeclientSocket

Server (running on hostid) Client

send request usingclientSocketread request from

connectionSocket

write reply toconnectionSocket

TCP connection setup

Page 27: Networking in java

Shravan Upadhayay

TCPClient.javaimport java.io.*; import java.net.*;

class TCPClient { public static void main(String argv[]) throws Exception{         String sentence;         String modifiedSentence;

BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));

Socket clientSocket = new Socket("hostname", 6789);        

DataOutputStream outToServer =          new DataOutputStream(clientSocket.getOutputStream());

Page 28: Networking in java

Shravan Upadhayay

TCPClient.javaBufferedReader inFromServer =

          new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));

        sentence = inFromUser.readLine();

        outToServer.writeBytes(sentence + '\n');

        modifiedSentence = inFromServer.readLine();

        System.out.println("FROM SERVER: " + modifiedSentence);

      clientSocket.close();                    }

}

Page 29: Networking in java

Shravan Upadhayay

TCPServer.javaimport java.io.*; import java.net.*; class TCPServer {   public static void main(String argv[]) throws Exception

    {       String clientSentence;       String capitalizedSentence;

 ServerSocket welcomeSocket = new

ServerSocket(6789);  

while(true) {

Socket connectionSocket = welcomeSocket.accept();

           BufferedReader inFromClient = new BufferedReader(new

InputStreamReader(connectionSocket.getInputStream()));

Page 30: Networking in java

Shravan Upadhayay

TCPServer.java

            DataOutputStream  outToClient =              new DataOutputStream(connectionSocket.getOutputStream());

           clientSentence = inFromClient.readLine();

           capitalizedSentence = clientSentence.toUpperCase() + '\n';

outToClient.writeBytes(capitalizedSentence);         } }

}