Вы находитесь на странице: 1из 11

Java Networking

Computers running on the Internet communicate to each other using either the Transmission Control
Protocol (TCP) or the User Datagram Protocol (UDP), as this diagram illustrates:

When you write Java programs that communicate over the network, you are programming at the
application layer. Typically, you don't need to concern yourself with the TCP and UDP layers. Instead, you
can use the classes in the java.net package. These classes provide system-independent network
communication.

TCP
Definition:
TCP (Transmission Control Protocol) is a connection-based protocol that provides a reliable flow of
data between two computers.

When two applications want to communicate to each other reliably, they establish a connection and
send data back and forth over that connection. This is analogous to making a telephone call.

TCP provides a point-to-point channel for applications that require reliable communications. 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. When HTTP is used to read
from a URL, the data must be received in the order in which it was sent. Otherwise, you end up with a
jumbled HTML file, a corrupt zip file, or some other invalid information.

UDP
Definition:

UDP (User Datagram Protocol) is a protocol that sends independent packets of data, called datagrams,
from one computer to another with no guarantees about arrival. UDP is not connection-based like TCP.

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 sendi ng 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.
Note:

Many firewalls and routers have been configured not to allow UDP packets. If you're having trouble connecting
to a service outside your firewall, or if clients are having trouble connecting to your service, ask your system
administrator if UDP is permitted.

Understanding Ports
Generally speaking, 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. So how does the computer know to which application to forward the
data? Through the use of ports.

Definition:

The TCP and UDP protocols use ports to map incoming data to a particular process running on a computer.

Port numbers range from 0 to 65,535 because ports are represented by 16-bit numbers. The port numbers
ranging from 0 - 1023 are restricted; they are reserved for use by well-known services such as HTTP and FTP
and other system services. These ports are called well-known ports. Your applications should not attempt to
bind to them.

Networking Classes in the JDK


Through the classes in java.net, Java programs can use TCP or UDP to communicate over the Internet.
The URL, URLConnection, Socket, and ServerSocket classes all use TCP to communicate over the
network. The DatagramPacket, DatagramSocket, and MulticastSocketclasses are for use with UDP.

Working with URLs


URL is the acronym for Uniform Resource Locator. It is a reference (an address) to a resource on the Internet.
You provide URLs to your favorite 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.

Java programs that interact with the Internet also may use URLs to find the resources on the Internet they wish
to access. Java programs can use a class called URL in the java.net package to represent a URL address.

Terminology Note:
The term URL can be ambiguous. It can refer to an Internet address or a URL object in a Java program. Where
the meaning of URL needs to be specific, this text uses "URL address" to mean an Internet address and
"URL object" to refer to an instance of the URL class in a program.

A URL has two main components:

 URL = {Protocol identifier :// Resource name}


 For the URL http://example.com, the protocol identifier is http.

 For the URL http://example.com, the resource name is example.com.

Resource name

Creating a URL
The easiest way to create a URL object is from a String that represents the human-readable form of the URL
address. This is typically the form that another person will use for a URL. In your Java program, you can use
a String containing this text to create a URL object:

URL myURL = new URL("http://example.com/");

Parsing a URL
The URL class provides several methods that let you query URL objects. You can get the protocol, authority,
host name, port number, path, query, filename, and reference from a URL using these accessor methods:

getProtocol

Returns the protocol identifier component of the URL.

getAuthority

Returns the authority component of the URL.

getHost
Returns the host name component of the URL.

getPort

Returns the port number component of the URL. The getPort method returns an integer that is the
port number. If the port is not set, getPort returns -1.

getPath

Returns the path component of this URL.

getQuery

Returns the query component of this URL.

getFile

Returns the filename component of the URL. The getFile method returns the same as getPath,
plus the concatenation of the value of getQuery, if any.

Example

// File Name : URLDemo.java


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

public class URLDemo {

public static void main(String [] args)


{
try {
URL url = new URL("https://docs.oracle.com/javase/tutorial/networking/urls/urlInfo.html");

System.out.println("URL is " + url.toString());


System.out.println("protocol is " + url.getProtocol());
System.out.println("authority is " + url.getAuthority());
System.out.println("file name is " + url.getFile());
System.out.println("host is " + url.getHost());
System.out.println("path is " + url.getPath());
System.out.println("port is " + url.getPort());
System.out.println("default port is " + url.getDefaultPort());
System.out.println("query is " + url.getQuery());
System.out.println("ref is " + url.getRef());
}catch(IOException e) {
e.printStackTrace();
}
}
}
Reading Directly from a URL
import java.net.*;
import java.io.*;

class OpenStreamTest
{
public static void main(String args[]) {
try {
URL yahoo = new URL("http://www.yahoo.com/");
DataInputStream dis;
String inputLine;

dis = new DataInputStream(yahoo.openStream());


while ((inputLine = dis.readLine()) != null) {
System.out.println(inputLine);
}
dis.close();
} catch (MalformedURLException me) {
System.out.println("MalformedURLException: " + me);
} catch (IOException ioe) {
System.out.println("IOException: " + ioe);
}
}
}

Reading from and Writing to a URLConnection


The URLConnection class contains many methods that let you communicate with the URL over the
network. URLConnection is an HTTP-centric class; that is, many of its methods are useful only when you are
working with HTTP URLs. However, most URL protocols allow you to read from and write to the connection.

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

public class DisplayData {


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

URL url=new URL("http://127.0.0.1:8080/apex/f?p=4550:11:5195932208513008::NO:::");


URLConnection urlcon=url.openConnection();

InputStream stream=urlcon.getInputStream();
int i;
while((i=stream.read())!=-1){
System.out.print((char)i);
}

}catch(Exception e){System.out.println(e);}
}
}

Writing to a URLConnection
Many HTML pages contain forms — text fields and other GUI objects that let you enter data to send to
the server. After you type in the required information and initiate the query by clicking a button, your Web
browser writes the data to the URL over the network. At the other end the server receives the data, processes
it, and then sends you a response, usually in the form of a new HTML page.

Many of these HTML forms use the HTTP POST METHOD to send data to the server. Thus writing to
a URL is often called posting to a URL. The server recognizes the POST request and reads the data sent from
the client.

For a Java program to interact with a server-side process it simply must be able to write to a URL, thus
providing data to the server. It can do this by following these steps:

1. Create a URL.
2. Retrieve the URLConnection object.

3. Set output capability on the URLConnection.

4. Open a connection to the resource.

5. Get an output stream from the connection.

6. Write to the output stream.

7. Close the output stream.


Inet Address
Inet Address encapsulates both numerical IP address and the domain name for that address.
Inet address can handle both IPv4 and Ipv6 addresses. Inet Address class has no visible
constructor. To create an inet Address object, you have to use Factory methods.
Three commonly used Inet Address factory methods are.

1. static InetAddress getLocalHost() throws UnknownHostException

2. static InetAddress getByName (String hostname) throws UnknownHostException

3. static InetAddress[ ] getAllByName (String hostname) throws UnknownHostException

import java.net.*;
class Test
{
public static void main(String[] args)
{
InetAddress address = InetAddress.getLocalHost();
System.out.println(address);
address = InetAddress.getByName("www.yahoo.com");
System.out.println(address);
InetAddress sw[] = InetAddress.getAllByName("www.google.com");
for(int i=0; i< sw.length; i++)
{
System.out.println(sw[i]);
}
}
}

Output
Welcome-PC/59.161.87.227
www.yahoo.com/208.91.198.55
www.google.com/74.125.236.115
www.google.com/74.125.236.116
www.google.com/74.125.236.112
www.google.com/74.125.236.113
www.google.com/74.125.236.114
www.google.com/2404:6800:4009:802:0:0:0:1014

import java.io.*;
import java.net.*;
public class InetDemo{
public static void main(String[] args){
try{
InetAddress ip=InetAddress.getByName("www.google.com");

System.out.println("Host Name: "+ip.getHostName());


System.out.println("IP Address: "+ip.getHostAddress());
}catch(Exception e){System.out.println(e);}
}
}

Socket and ServerSocket Class

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:

1. IP Address of Server, and


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

Method Description

1) public InputStream getInputStream() returns the InputStream attached with this socket.

2)public OutputStream getOutputStream() returns the OutputStream attached with this socket.

3) public synchronized void close() closes this socket

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

Important methods

Method Description

1) public Socket accept() returns the socket and establish a connection between server
and client.

2)public synchronized void closes the server socket.


close()

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

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 DataOutputStream(s.getOutputStream());

dout.writeUTF("Hello Server");
dout.flush();

dout.close();
s.close();

}catch(Exception e){System.out.println(e);}
}
}

Вам также может понравиться