Java Networking
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.
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.
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:
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
getAuthority
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
getQuery
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
class OpenStreamTest
{
public static void main(String args[]) {
try {
URL yahoo = new URL("http://www.yahoo.com/");
DataInputStream dis;
String inputLine;
import java.io.*;
import java.net.*;
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.
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");
Java Socket programming is used for communication between the applications running on
different JRE.
Socket and ServerSocket classes are used for connection-oriented socket programming and
DatagramSocket and DatagramPacket classes are used for connection-less socket
programming.
Method Description
1) public InputStream getInputStream() returns the InputStream attached with this socket.
2)public OutputStream getOutputStream() returns the OutputStream attached with 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.
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.*;
dout.writeUTF("Hello Server");
dout.flush();
dout.close();
s.close();
}catch(Exception e){System.out.println(e);}
}
}