Friday, 19 February 2016

Networking in JAVA

Networking in JAVA is best thing i used in JAVA. Those who are new with networking in JAVA should use only three basic things first. These things are Socket, Host name, and I/O streams. Socket is used for making connection, Host name is address and I/O streams for sending and receiving information. So here is our first and simplest example in JAVA networking.

package socket;
import java.util.*;


* This program makes a socket connection to the atomic
   clock in Boulder, Colorado, and prints

* the time that the server sends.


public class SocketTest {

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

try (Socket s = new Socket("", 13)) {

InputStream inStream = s.getInputStream();

Scanner in = new Scanner(inStream);

while (in.hasNextLine())


String line = in.nextLine();




The first line opens a socket, which is a network software abstraction that enables communication out of and into this program. We pass the remote address and the port number to the socket constructor. If the connection fails, an UnknownHostException is thrown. If there is another problem, an IOException occurs. Since UnknownHostException is a subclass of IOException and this is a sample program, we just catch the superclass.
Once the socket is open, the getInputStream method in returns an
InputStream object that you can use just like any other stream. Once you have grabbed the stream, this program simply prints each input line to standard output. This process continues until the stream is finished and the server disconnects.

Note: The Java platform also supports the User Datagram Protocol (UDP), which can be used to send packets (also called datagrams) with much less overhead than that of TCP. The drawback is that packets need not be delivered in sequential order to the receiving application and can even be dropped altogether. It is up to the recipient to put the packets in order and to request retransmission of missing packets. UDP is well suited for applications in which missing packets can be tolerated —for example, for audio or video streams or continuous measurements.