Você está na página 1de 13

Chapter 9 Networking

The Java platform is extremely preferable to write an application program require to


communicate with the resources on network. Java, mainly focuses on the networking
relating the description of the networking capabilities of the Java platform and second
one is describes networking in a very simple manner that how to use URLs, sockets,
and datagram’s.
In Java, there is a java.net package provides the network support. All the classes for
making a network program are defined in the java.net package.

What we will learn in networking chapter?

• Networking and Networking Terminology (IpAddress , Protocol and soon..)

• Socket Programming (Connection-oriented)

• URL class

• InetAddress class

• DatagramSocket and DatagramPacket (Connection-less)

Networking:

Networking is a concept of connecting two or more computing devices together so that


we can share resources.

Advantage:

• sharing resources

• centralize software management

Networking Terminology:

There are some networking terminologies given below:

 IP Address
 HostName
 Protocol
 Port Number
 MAC Address
 Connection-oriented and connectionless protocol
 Socket

IP Address:
IP address is a unique number assigned to a node of a network e.g. 192.168.0.1 .

the default Ip address of a computer is 127.0.0.1 and it's mapped host name is
localhost.

Range of IP address:- 0.0.0.0 to 255.255.255.255


HostName:-

Host name is the alias name of the computers. as human being we cannot remember
comupters with numbers. so each computer Ip address is mapped with a string called
hostname.

Note:-

In the projects it is not recomnded to use IPAddresss in sending request,instead we


should use it's hostname.

Example:-

192.168.2.19 NareshIT19

192.168.2.20 NareshIT20

Below are the Dos commands

to know IP address--ipconfig

Hostname------hostname

Protocol:

protocol is a set of instutcions to send request and receive response via network.

Types of protocols:-

1.TCP/IP : Tcp/IP is a connection oriented and secured protocol, for every request
we will get response.

Tcp/Ip protocol are divide into four protocols based on type

of the data transfer.

1. Http

2. Https

3. Ftp

4. Smtp

2. UDP--UserDatagram protocol:

UDP is connection less protocol, and it is nonsecured protocol. using this protocol we
cannot guarantee data transfer.

Ex:-

Mobile and radio communications.

Socket Programming:
A socket is one end-point of a two-way communication link between two
programs running on the network. Socket classes are used to represent the
connection between a client program and a server program. The java.net
package provides two classes--Socket and ServerSocket--that implement the
client side of the connection and the server side of the connection, respectively.

Socket class:

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

Commonly used methods of Socket class:

1) public InputStream getInputStream()

2) public OutputStream getOutputStream()

3) public synchronized void close()

ServerSocket class:

The ServerSocket class can be used to create a server socket. This object is used to
establish communication with the clients.

Commonly used methods of ServerSocket class:

1) public Socket accept()

1) public InputStream getInputStream()

2) public OutputStream getOutputStream()

3) public synchronized void close()

Q) What is server?
ans: a server is a networking program that can receive a request from client and it can send response to
the client.
Q) What is client?
ans: a client is also a networking program that can send a request to the server and it can receive a
response from the server.
Q) How to develop client and server programs?
To develop client and server program we use ServerScoket and Socket classes of java.net package and
the following steps:

Steps to create a server program Steps to create a client program


step1: step1: give connection request to server program
Register server port number or Bind server port Socket cs = new Socket("192.168.1.1",7070);
number step2: get output stream and connect it to print
ServerSocket server = new ServerSocket(7070); stream and send "hai" to server
step2: wait for client connection request & accept OuputStream out = cs.getOutputStream();
it PrintStream ps = new PrintStream(out);
Socket ss = server.accept(); ps.println("hai");
step3: getinput stream and connect to scanner and step3:
read msg given by client getinput stream and connect to scanner and read
InputStream in = ss.getInputStream(); msg given by server
Scanner sc = new Scanner(in); InputStream in = cs.getInputStream();
String msg = sc.nextLine(); Scanner sc = new Scanner(in);
step4: get output stream and connect to String msg = sc.nextLine();
printstream and send byedear to client S.o.pln(msg);
ouputStream out = ss.getOuputStream(); step4:
PrintStream ps = new PrintStream(out); in.close(); ps.close(); out.close(); cs.close();
ps.println("byedear");
S.o.pln(msg);
step5:
in.close(); ps.close(); out.close(); ss.close();

Example of client-server Socket Programming:

Listening 9.1 showing MyServer.java


import java.io.DataInputStream;

import java.net.Socket;

import java.net.ServerSocket;

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);

Listening 9.2 showing MyClient.java

import java.io.DataOutputStream;

import java.net.Socket;

public class MyClient {

public static void main(String[] args) {

try{

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

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

dout.writeUTF("Hello Server");

dout.flush();

dout.close();

s.close();
}catch(Exception e){

System.out.println(e);

To execute above Socket programs open two command prompts and execute each
program at each command prompt as displayed in the below figure. First execute
server app and then after client app.

Note :

In the above example client sending only one request.

* to send the multiple requests and get the Multiple responses from server put the
logic inside an infinite loop (i.e. while (true)).

See the next example to multiple requests and get multiple responses from server.

Listening 9.3 showing ChatClient.java

import java.io.*;

import java.net.*;

public class ChatClient{


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

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

OutputStream os=s.getOutputStream();

DataOutputStream dos=new DataOutputStream(os);

InputStream is=s.getInputStream();

DataInputStream dis=new DataInputStream(is);

//to accept dynamic inputdata from keyboard

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

while(true){

System.out.println("Enter your Request:");

String data1=br.readLine();

dos.writeUTF(data1);

String data2=dis.readUTF();

System.out.println("Msg from server :"+data2);

if(data1.equalsIgnoreCase("bye"))

break;

Listening 9.4 showing ChatServer.java

import java.io.*;

import java.net.*;

public class ChatServer {

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


ServerSocket ss=new ServerSocket(5566);

System.out.println("Server Started..");

Socket s=ss.accept();

InputStream is=s.getInputStream();

DataInputStream dis=new DataInputStream(is);

OutputStream os=s.getOutputStream();

DataOutputStream dos=new DataOutputStream(os);

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

while(true){

String data1=dis.readUTF();

System.out.println("Msg From Client :"+data1);

String data2=br.readLine();

dos.writeUTF(data2);

if(data2.equalsIgnoreCase("Ok Bye"))

break;

Output:
URL class:
The URL class represents a URL. URL is an acronym for Uniform Resource Locator. It
points to a resource on the World Wide Web. For example:

http://www.nareshit.com/index.jsp

A URL contains many informations:

• Protocol: In this case, http is the protocol.

• Server name or IP Address: In this case, www.nareshit.com is the server name.

• Port Number: It is an optional attribute. If we write


http://www.nareshit.com:80/index.jsp is the port number.

• File Name or directory name: In this case, index.jsp is the file name.

Commonly used methods of URL class:

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

Example of URL class:

Listening 9.5 showing URLDemo.java

import java.net.URL;

public class URLDemo{

public static void main(String[] args){

try{

URL url=new URL("http://www.nareshit.com/index.jsp");

System.out.print("Protocol: "+url.getProtocol());

System.out.print("Host Name: "+url.getHost());

System.out.print("Port Number: "+url.getPort());

System.out.print("File Name: "+url.getFile());

catch(Exception e){

System.out.println(e);
}

Output :

InetAddress class:

The java.net.InetAddress class represents an IP address. The Inet Address class


provides methods to get the IP of any host name.

Commonly used methods of InetAddress class:

• public static InetAddress getByName(String host) throws


UnknownHostException: it returns the IP of the given host.

• public static InetAddress getLocalHost() throws UnknownHostException: it


returns the LocalHost IP and name.

• public String getHostName(): it returns the host name of the IP address.

• public String getHostAddress(): it returns the IP address in string format.

DatagramSocket and DatagramPacket (Networking):

datagrams sends and receives completely independent packets of information and they
also don?t need a dedicated point-to-point channel.
Datagrams are simply a bundles of information data passed between machines. Java
implements datagrams on top of the UDP protocol by using the following classes which
are in java.net package as well as define as under :

 DatagramSocket
 DatagramPacket

DatagramSocket class:

The DatagramSocket class represents a connection-less socket for sending and


receiving datagram packets. Datagram is basically an information but there is no
gurantee of its content, arrival or arrival time. The DatagramSocket and
DatagramPacket classes are used for connection-less socket programming.

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.

DatagramPacket class:

The DatagramPacket is message that can be sent or received. If you send multiple
packet, it may arrive in any order. Moreover, 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 constructor is used to send the packets.

Listening 9.5 showing Sending DatagramPacket by DatagramSocket

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();

Listening 9.6 showing Receiving DatagramPacket by DatagramSocket

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();

Summary :
 Client-server architecture can be considered as a network environment that
exchanges information between a server machine and a client machine where
server has some resources that can be shared by different clients.
 In common language we can say that the socket is one of the most primal
technologies of computer networking. Sockets are just like an end-point of two-
way communication, which allow applications to communicate using network
hardware and operating systems.
 server is a networking program that can receive a request from client and it can
send response to the client.
 client is also a networking program that can send a request to the server and it
can receive a response from the server.
 To develop client and server program we use ServerScoket and Socket classes of
java.net package
 A URL (Uniform Resource Locator) is the address of a resource on the Internet.
In java network programming we can use URLs to connect and retrieve
information over the Internet.

 Datagrams are simply a bundles of information data passed between machines.


Java implements datagrams on top of the UDP protocol by using the following
classes which are present in java.net package.

 DatagramSocket

 DatagramPacket

Você também pode gostar