• No results found

NETWORK PROGRAMMING

N/A
N/A
Protected

Academic year: 2020

Share "NETWORK PROGRAMMING"

Copied!
43
0
0

Loading.... (view fulltext now)

Full text

(1)

1

NETWORK

(2)

Java - Networking

The term network programming refers to writing programs that execute across multiple devices (computers), in which the devices are all connected to each other using a network.

The java.net package of the J2SE APIs contains a collection of classes and interfaces that provide the low-level communication details, allowing you to write programs that focus on solving the problem at hand.

The java.net package provides support for the two common network protocols −

TCP − TCP stands for Transmission Control Protocol, which allows for

reliable communication between two applications. TCP is typically used over the Internet Protocol, which is referred to as TCP/IP.

UDP − UDP stands for User Datagram Protocol, a connection-less protocol

(3)

Socket Programming

■ Sockets provide the communication mechanism between two

computers using TCP. A client program creates a socket on its end of the communication and attempts to connect that socket to a server.

■ When the connection is made, the server creates a socket

object on its end of the communication. The client and the server can now communicate by writing to and reading from the socket.

■ The java.net.Socket class represents a socket, and the

java.net.ServerSocket class provides a mechanism for the server program to listen for clients and establish connections with them

(4)

The following steps occur when establishing a TCP connection between two computers using sockets −

■ The server instantiates a ServerSocket object, denoting which port number

communication is to occur on.

■ The server invokes the accept() method of the ServerSocket class. This method

waits until a client connects to the server on the given port.

■ After the server is waiting, a client instantiates a Socket object, specifying the

server name and the port number to connect to.

■ The constructor of the Socket class attempts to connect the client to the specified

server and the port number. If communication is established, the client now has a Socket object capable of communicating with the server.

■ On the server side, the accept() method returns a reference to a new socket on the

server that is connected to the client's socket.

After the connections are established, communication can occur using I/O streams. Each socket has both an OutputStream and an InputStream. The client's OutputStream is connected to the server's InputStream, and the client's InputStream is connected to the server's OutputStream.

(5)

ServerSocket Class Methods

The java.net.ServerSocket class is used by server applications to obtain a port and listen for

client requests.

■ The ServerSocket class has four constructors −

5

If the ServerSocket constructor does not throw an exception, it means that your application has successfully bound to the specified port and is ready for client requests.

(6)

■ Following are some of the common methods of the ServerSocket class −

(7)

Socket Class Methods

7

The java.net.Socket class represents the socket that both the client and the server use to communicate with

each other. The client obtains a Socket object by instantiating one, whereas the server obtains a Socket object from the return value of the accept() method.

■ The Socket class has five constructors that a client uses to connect to a server −

When the Socket constructor returns, it does not simply instantiate a Socket object but it actually attempts to connect to the specified server and port.

(8)
(9)

Java Networking

Java Networking is a concept of connecting two or

more computing devices together so that we can share

resources.

Java socket programming provides facility to share

data between different computing devices.

Advantage of Java Networking

sharing resources

centralize software management

(10)

Java Networking Terminology

The widely used java networking terminologies are

given below:

IP Address

Protocol

Port Number

MAC Address

Connection-oriented and connection-less protocol

Socket

(11)

1) IP Address

IP address is a unique number assigned to a node

of a network e.g. 192.168.0.1 . It is composed of

octets that range from 0 to 255.

It is a logical address that can be changed.

(12)

2) Protocol

A protocol is a set of rules basically that is followed

for communication. For example:

TCP

FTP

Telnet

SMTP

(13)

3) Port Number

The port number is used to uniquely identify

different applications. It acts as a communication

endpoint between applications.

The port number is associated with the IP address

for communication between two applications.

(14)

4) MAC Address

MAC (Media Access Control) Address is a

unique identifier of NIC (Network Interface

Controller). A network node can have multiple

NIC but each with unique MAC.

(15)

5) Connection-oriented and

connection-less protocol

In connection-oriented protocol, acknowledgement is

sent by the receiver. So it is reliable but slow. The

example of connection-oriented protocol is TCP.

But, in connection-less protocol, acknowledgement is

not sent by the receiver. So it is not reliable but fast.

The example of connection-less protocol is UDP.

(16)

6) Socket

A socket is an endpoint between two way

(17)

Java Socket Programming

■ 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.

(18)

Socket class

A socket is simply an endpoint for communications between the machines. The Socket class can be used to create a socket.

(19)

ServerSocket class

19

■ The ServerSocket class can be used to create a server socket.

This object is used to establish communication with the clients.

(20)

Steps of Socket programming

Create Socket (server & client side)

Listen the Socket

Read & write data on stream in socket

Close the socket and stream

(21)

Creating A Socket

For client:

Socket MyClient;

MyClient = new Socket("Machine name", PortNumber);

■ Where Machine name is the machine you are trying to

open a connection to, and PortNumber is the port (a

number) on which the server you are trying to connect to is running.

■ When selecting a port number, you should note that port

numbers between 0 and 1,023 are reserved for

privileged users (that is, super user or root). These port numbers are reserved for standard services, such as

email, FTP, and HTTP. When selecting a port number for your server, select one that is greater than 1,023!

(22)

Client with exception handling

Socket MyClient;

try

■ {

MyClient = new Socket("Machine name", PortNumber);

■ }

catch (IOException e)

(23)

For the Server:

ServerSocket MyService;

try

■ {

MyService = new ServerSocket(PortNumber);

■ }

catch (IOException e)

{ System.out.println(e); }

(24)

Listining the Socket

■ When implementing a server you also need to create a

socket object from the ServerSocket in order to listen for and accept connections from clients.

Socket clientSocket = null;

Try ■ { ■ serviceSocket = MyService.accept(); ■ } ■ catch (IOException e) { System.out.println(e); }

(25)

Taking Input & Output from Socket

■ In the client side, you can use the DataInputStream class to create

an input stream to receive response from the server:

DataInputStream input;

try {

input = new DataInputStream(MyClient.getInputStream()); }

catch (IOException e)

{ System.out.println(e); }

■ The class DataInputStream allows you to read lines of text and Java

primitive data types in a portable way.

■ It has methods such

as read, readChar, readInt,readDouble, and readLine,.

(26)

■ On the server side, you can use DataInputStream to receive input from the client:

DataInputStream input try

{

input = new DataInputStream(serviceSocket.getInputStream()); } catch (IOException e)

{

System.out.println(e);

(27)

■ On the client side, you can create an output stream to send information to the server socket using the

class PrintStream or DataOutputStream of java.io: PrintStream output;

try {

output = new PrintStream(MyClient.getOutputStream()); }

catch (IOException e)

{

System.out.println(e); }

■ The class PrintStream has methods for displaying textual

representation of Java primitive data types. Its Write and println methods are important here

(28)

■ Also, you may want to use the DataOutputStream:

DataOutputStream output;

try {

output = new DataOutputStream(MyClient.getOutputStream()); }

catch (IOException e)

{ System.out.println(e); }

■ The class DataOutputStream allows you to write Java

primitive data types; many of its methods write a single Java primitive type to the output stream. The

(29)

Close the socket

■ You should always close the output and input stream

before you close the socket.

■ On the client side:

try { output.close(); input.close(); MyClient.close(); } catch (IOException e) { System.out.println(e); } 29

(30)

■ On the server side: try { output.close(); input.close(); serviceSocket.close(); MyService.close(); } catch (IOException e) { System.out.println(e); }

(31)

Example of Java Socket Programming

File: MyServer.java

31

Let's see a simple of java socket programming in which client sends a text and server receives it .

import java.io.*;

import java.net.*;

public class MyServer {

public static void main(String[] args){

try{

ServerSocket ss=new ServerSocket(6666); ■ Socket s=ss.accept();//establishes connection

DataInputStream dis=new DataInputStream(s.getInputStream()); ■ String str=(String)dis.readUTF(); ■ System.out.println("message= "+str); ■ ss.close(); ■ }catch(Exception e){System.out.println(e);} ■ } ■ }

(32)

File: MyClient.java

import java.io.*; import java.net.*;

public class MyClient {

public static void main(String[] args) { try{

Socket s=new Socket("localhost",6666); DataOutputStream dout=new DataOutputStre

am(s.getOutputStream()); ■ dout.writeUTF("Hello Server"); ■ dout.flush(); ■ dout.close(); ■ s.close(); ■ }catch(Exception e){System.out.println(e);} ■ } ■ }

Let's see a simple of java socket programming in which client sends a text and server receives it .

import java.io.*; import java.net.*;

public class MyServer {

public static void main(String[] args){ try{

ServerSocket ss=new ServerSocket(6666); Socket s=ss.accept();//establishes connection DataInputStream dis=new DataInputStream(s.ge tInputStream()); String str=(String)dis.readUTF(); System.out.println("message= "+str); ss.close(); }catch(Exception e){System.out.println(e);} } }

(33)

Output

To execute this program open two command prompts and execute each program at each command prompt as displayed in the below figure.

(34)

Example of Java Socket Programming (Read-Write both side)

import java.net.*; import java.io.*; class MyServer{

public static void main(String args[])throws Exception{

ServerSocket ss=new ServerSocket(3333); Socket s=ss.accept();

DataInputStream din=new DataInputStream(s.getInputStream()); DataOutputStream dout=new DataOutputStream(s.getOutputStream()); BufferedReader br=new BufferedReader(new InputStreamReader(System.i

n)); String str="",str2=""; while(!str.equals("stop")){ str=din.readUTF(); System.out.println("client says: "+str); str2=br.readLine(); dout.writeUTF(str2); dout.flush(); } din.close(); s.close(); ss.close(); }} import java.net.*; import java.io.*; class MyClient{

public static void main(String args[])throws Exceptio n{

Socket s=new Socket("localhost",3333);

DataInputStream din=new DataInputStream(s.getInput Stream());

DataOutputStream dout=new DataOutputStream(s.get OutputStream());

BufferedReader br=new BufferedReader(new InputStr eamReader(System.in)); String str="",str2=""; while(!str.equals("stop")){ str=br.readLine(); dout.writeUTF(str); dout.flush(); str2=din.readUTF(); System.out.println("Server says: "+str2); } dout.close(); s.close();

(35)

File: MyClient.java

import java.net.*; import java.io.*; class MyClient{

public static void main(String args[])throws Exception{

Socket s=new Socket("localhost",3333);

DataInputStream din=new DataInputStream(s.getInputStream());

DataOutputStream dout=new DataOutputStream(s.getOutputStream());

BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); ■ ■ String str="",str2=""; while(!str.equals("stop")){ ■ str=br.readLine(); ■ dout.writeUTF(str); ■ dout.flush(); ■ str2=din.readUTF(); ■ System.out.println("Server says: "+str2); ■ } ■ ■ dout.close(); ■ s.close(); ■ }} 35

(36)

Socket Types

There are two widely used socket types, stream sockets, and datagram sockets.

■ Stream sockets treat communications as a continuous stream

of characters, while datagram sockets have to read entire messages at once. Each uses its own communications protocol. Stream sockets use TCP (Transmission Control Protocol), which is a reliable, stream oriented protocol.

■ Datagram sockets use UDP (Unix Datagram Protocol), which

is unreliable and message oriented. A second type of connection is a datagram socket. You might want to use a datagram socket in cases where there is only one message being sent from the client to the server, and only one message

(37)

Difference between Stream socket and Datagram socket

There are several differences between a datagram socket and a stream socket.

■ Datagrams are unreliable, which means that if a packet of information gets lost

somewhere in the Internet, the sender is not told (and of course the receiver does not know about the existence of the message). In contrast, with a stream socket, the underlying TCP protocol will detect that a message was lost because it was not acknowledged, and it will be retransmitted without the process at either end knowing about this.

■ Message boundaries are preserved in datagram sockets. If the sender sends a

datagram of 100 bytes, the receiver must read all 100 bytes at once. This can be contrasted with a stream socket, where if the sender wrote a 100 byte message, the receiver could read it in two chunks of 50 bytes or 100 chunks of one byte.

■ The communication is done using special system

calls sendto() andreceivefrom() rather than the more generic read() and write().

■ There is a lot less overhead associated with a datagram socket because connections

do not need to be established and broken down, and packets do not need to be acknowledged. This is why datagram sockets are often used when the service to be provided is short, such as a time-of-day service.

(38)

Java DatagramSocket and

DatagramPacket

Java DatagramSocket and DatagramPacket

classes are used for connection-less socket

programming

(39)

Java DatagramSocket class

Java DatagramSocket class represents a connection-less socket for

sending and receiving datagram packets.

A datagram is basically an information but there is no guarantee of its content, arrival or arrival time.

Commonly used Constructors of DatagramSocket class

DatagramSocket() throws SocketEeption: it creates a datagram socket

and binds it with the available Port Number on the localhost machine.

DatagramSocket(int port) throws SocketEeption: it creates a datagram

socket and binds it with the given Port Number.

DatagramSocket(int port, InetAddress address) throws

SocketEeption: it creates a datagram socket and binds it with the specified

port number and host address.

(40)

Java DatagramPacket class

Java DatagramPacket is a message that can be sent or

received. If you send multiple packet, it may arrive in any order. Additionally, packet delivery is not guaranteed.

Commonly used Constructors of DatagramPacket class

DatagramPacket(byte[] barr, int length): it creates a

datagram packet. This constructor is used to receive the packets.

DatagramPacket(byte[] barr, int length, InetAddress

address, int port): it creates a datagram packet. This

(41)

Example of Sending DatagramPacket by

DatagramSocket

■ //DSender.java

import java.net.*;

public class DSender{

public static void main(String[] args) throws Exception { DatagramSocket ds = new DatagramSocket();

■ String str = "Welcome java";

■ InetAddress ip = InetAddress.getByName("127.0.0.1"); ■

DatagramPacket dp = new DatagramPacket(str.getBytes(), str.length(), ip, 3000);

■ ds.send(dp); ■ ds.close(); ■ } ■ } 41

(42)

Example of Receiving DatagramPacket by

DatagramSocket

■ //DReceiver.java

import java.net.*;

public class DReceiver{

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 str = new String(dp.getData(), 0, dp.getLength()); ■ System.out.println(str);

■ ds.close(); ■ }

(43)

References

Related documents

java –cp hsqldb.jar org.hsqldb.WebServer -port 8181 -silent false -database LA_BASE.. • Serveur socket

In CS Relationship “most of the application processing is done on a computer (client side), which obtains application services (such as database services) from another

Tai means belt, and this channel follows a course th a t encircles the waist, binding up the Yin and Yang channels.... It finally moves across the chin and cheekbone and

Fulfilment of birthday for someone special day and keep you are heart such an inspiration birthday you my dear mother like the best heart racing and funny and wonderful?. Flame to

GU Ventures menar också på att selektering genom andra investerare inte utgör starka motiv till varför bolaget genomför syndikatinvetseringar, då deras underlag och restriktioner

The current study examined the effects of information complexity (data amount and task complexity) and visual presentation as a key aspect of usability and human factors on

(B) the adsorption at a single site on the surface may involve multiple molecules at the same time.. (C) the mass of gas striking a given area of surface is proportional to the

Eight approved Acala varieties were evaluated for yield performance; Pima S-6 and five other advanced lines from the USDA Pima program were tested; 19 experimental USDA