Sie sind auf Seite 1von 9

Complete Java Networking Explained with Simple

Examples
Discussion in 'Java' started by techgeek.in, Feb 24, 2010.

1.
techgeek.inNew Member
JOINED:

Dec 20, 2009

MESSAGES:

572

LIKES RECEIVED:

19

TROPHY POINTS:

OCCUPATION:

EOC (exploitation of computers)..i m a Terminator.

LOCATION:

Not an alien!! for sure

HOME PAGE:

http://www.techgeek.in

In Java, networking is performed using Transmission Control Protocol/Internet


Protocol (TCP/IP) or the User Datagram Protocol (UDP).

Java provides a low-level control on the connection, allowing you to customize it


according to your requirements. The package containing networking classes, called
java.net, is shipped as part of the Java Development Kit (JDK). In Java, TCP
connections are established using sockets and server sockets. These connections
allow you to send and receive data to a Web Site. On the other hand, broadcast
messages known as datagrams use the UDP. Datagrams are encapsulated in a
datagram packet and sent using a datagram socket. URLs can be created and
modified using the URL class methods of Java.
Socket Overview

A socket forms the interface between the protocol and client for communication. A
Java socket forms the base for data transmission between two computers using
TCP/IP. The socket specifies the site address and the connection port. When
packets reach a client or server, they are routed to the destination port specified in
packet header.

The java.net Package

The java.net package contains the classes and interfaces required for networking.
Some important classes are MulticastSocket, ContentHandler, URLServerSocket,
Socket, InetAddress, URLConnection, DatagramSocket, and DatagramPacket.
Some important interfaces in the java.net package are ContentHandlerFactory,
SocketImplFactory, FileNameMap, URLStreamHandlerFactory, and SocketOptions.
InetAddress

This class encapsulates the numerical IP address and the domain name for the
address. Factory methods of a class allow you to call the method without referencing
the object. The factory methods of this class are:
getLocalHost() method: Returns the name of the local
computer
getByName() method: Returns the address by the Domain name
getAllByName() method: Returns all the addresses by their
domain name
The instance methods of a class are methods that can be called
from an object only. The instance methods for the class are:
getAddress() method: Returns a four-element byte array that
represents the objects IP address in network byte order
getHostAddress() method: Returns the host address
getHostName() method: Returns the hostname that is
associated with the host address.

The TCP/IP Client Socket

A TCP/IP client socket is used to create a reliable, bi-directional, stream-based


connection between two computers on a network. The client socket is implemented
by creating an instance of the Socket class. It is designed to connect to the server
and initialize protocol exchanges.

Methods to Create TCP Client Sockets

An object of the Socket class can be created by these methods:


By specifying the hostname and port number as follows:

Socket (String hostname1, int port1)

Where, hostname1 is a string type variable that refers to the destination address and
port1 refers to the port number of the destination address. This method can throw
the exceptions, UnknownHostException or IOException, in case of errors.
By specifying an object of InetAddress and the port number as
follows:

Socket(InetAddress ipaddr1, int port1)

Where, ipaddr1 is object of the InetAddress class and port1 refers to the port number
of the destination. This method can throw the exception IOException, in case of
errors.
Methods of the Socket Class

InetAddress getInetAddress() -- Returns the InetAddress that is associated with


the socket object.

int getPort() -- Returns the port number on which the socket is connected

int getLocalPort() -- Returns the local port number on which the socket is created

InputStream getInputStream() -- Returns the InputStream associated with the


calling object.

OutputStream getOutputStream() -- Returns the OutputStream associated with the


calling object.

void close() -- Closes the InputStream() and OutputStream() of the socket.


Code:

//filename ExSocket.java
import java.io.*;
import java.net.*;
public class ExSocket {
public static void main(String args[]) throws UnknownHostException
{
try
{
Socket mySocket = new Socket("www.my-site.com",80);
System.out.println("Connection to: " +
mySocket.getInetAddress());
System.out.println("Port Number: " + mySocket.getPort());
System.out.println("Local Address: " +
mySocket.getLocalAddress());
System.out.println("Local Port: " +
mySocket.getLocalPort());
}
catch (UnknownHostException e)
{
System.out.println("Site not found!");
}
catch (SocketException e)
{
System.out.println("Socket error");
}
catch ( IOException e)
{
System.out.println("An I/O Exception Occurred!");
}
}
}

EXPLANATION:-

In this example, a connection to my-site.com on port 80 through sockets is opened.


You create a class called ExSocket and declare the main() method. To create an
object of the Socket class with the default constructor, specify the URL of the site
and the port number within a try block. When the socket is created and connected,
the System.out.println function prints the internal values of the socket that include the
URL, the port number it is connected to, the local address of the computer, and the
local port. The catch block traps the socket errors. Errors include UnknowException
for unknown errors, SocketException for socket errors, and IOException for I/O
errors.
The TCP/IP Server Socket

The TCP/IP server socket creates a socket that listens for incoming connections.
The server socket is implemented by creating an instance of the ServerSocket class.
The server socket creates a server on the system to detect client connections.

Methods to Create TCP Server Sockets

An instance of the ServerSocket class can create a server that accepts incoming
requests. An object of the ServerSocket class can be created using any one of these
methods:
Specify the port number in the int type. An example of this
method is:

ServerSocket(int port1)

Where, port1 is an integer, which can have any value between 0 and 65,536.
Specify the port number and maxQueue. maxQueue refers to
the number of connections the socket can leave pending before
refusing more connections.
An example of this method is:

ServerSocket(int port1, int maxQ)

Where, maxQ refers to an int value that specifies the number of connections it can
leave pending before refusing any more connections.
Specify the port number, maxQueue, and the local address. An
example of this method is:

ServerSocket(int port1, int maxQ, InetAddress address1)


Where, address1 refers to the IP address of the server on which the socket is
created.

Methods of the ServerSocket Class

socket accept() -- Accepts an incoming connection.

int getLocalPort() -- Returns the port number on which the server socket is
listening.
void close() -- Closes the server socket.
Code:

//Program to demonstrate ServerSockets


import java.io.*;
import java.net.*;
public class SerSocket
{
public static void main(String args[])
{
int port=1080;
try
{
ServerSocket mySocket = new ServerSocket(port);
System.out.println("Server initialized on port " + port);
mySocket.getLocalPort();
{
while(true)
mySocket.accept();
}
}
catch (SocketException e)
{
System.out.println("Socket error");
}
catch ( IOException e)
{
System.out.println("An I/O Exception Occurred!");
}
}
}

EXPLANATION:-

In this example, an instance of the ServerSocket class is created. The main()


function takes default arguments args[] and is encapsulated by the SerSocket class.
You create an object called mySocket of the ServerSocket class using its default
constructor by specifying the port number. Once the socket is initialized, the program
prints that the socket is listening on the port. The getLocalPort() function returns the
address of the port on the local computer. While the port is available, the socket
listens for incoming connections through the accept() function. The catch loop traps
any runtime exceptions.

TWO EXAMPLES
1. A PROGRAM ON ECHO SERVER

CLIENT SIDE CODE


Code:

import java.net.*;
import java.io.*;
class clientsock
{
public static void main(String args[]) throws IOException
{
System.out.println("sending request to server....");
Socket client=new Socket("127.0.0.1",1235);
System.out.println("successfully conneted");
BufferedReader br1=new BufferedReader(new
InputStreamReader(System.in));
PrintStream ps=new PrintStream(client.getOutputStream());
BufferedReader br=new BufferedReader(new
InputStreamReader(client.getInputStream()));
while(true)
{
System.out.println("input the data u want to send to echo
server: ");
String s=br1.readLine();
ps.println(s);
if(s.equals("exit"))
{
System.exit(1);
}
String st=br.readLine();
System.out.println("data returned by the server: ");
System.out.println(st);
}
}
}

SERVER SIDE CODE


Code:

import java.net.*;
import java.io.*;
class serversock
{
public static void main(String args[]) throws IOException
{
ServerSocket server=new ServerSocket(1235);
System.out.println("waiting for request from client");
Socket client=server.accept();
System.out.println("request accepted");

BufferedReader br=new BufferedReader(new


InputStreamReader(client.getInputStream()));
while(true)
{
String st=br.readLine();
if(st.equals("exit")==true)
{
System.out.println("connection with client is
lost....");
System.exit(1);
}
PrintStream ps=new PrintStream(client.getOutputStream());
ps.println(st);
}
}
}

2. A CHAT PROGRAM
CLIENT SIDE CODE
Code:

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

class clie implements Runnable


{
Thread t;
Socket client;
clie(Socket client)
{
this.client=client;
t=new Thread(this);
t.start();

}
public void run()
{
try{

BufferedReader br=new BufferedReader(new


InputStreamReader(client.getInputStream()));
while(true)
{
String st1=br.readLine();
System.out.println(" "+st1);
}

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

}
}
}

class clientsock
{
public static void main(String args[]) throws IOException
{
try{
System.out.println("sending request to peer....");
Socket client=new Socket("127.0.0.1",1300);
System.out.println("successfully conneted");
clie c=new clie(client);

BufferedReader br1=new BufferedReader(new


InputStreamReader(System.in));
PrintStream ps=new PrintStream(client.getOutputStream());
while(true)
{
String s=br1.readLine();
ps.println(s);
}
}
catch(Exception e)
{
System.out.println(e);
}
}
}

SERVER SIDE CODE


Code:

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

class serv implements Runnable


{
Thread t;
Socket client;
serv(Socket client)
{
this.client=client;
t=new Thread(this);
t.start();
}
public void run()
{
try
{
BufferedReader br=new BufferedReader(new
InputStreamReader(client.getInputStream()));
while(true)
{
String st1=br.readLine();
System.out.println("client: "+st1);
}
}
catch(IOException e)
{
System.out.println(e);

}
}
}

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

ServerSocket server=new ServerSocket(1300);


System.out.println("waiting for request from peer.....");
Socket client=server.accept();
serv s=new serv(client);
System.out.println("request accepted");
BufferedReader br2=new BufferedReader(new InputStreamReader(System.in));
PrintStream ps2=new PrintStream(client.getOutputStream());
while(true)
{
String st=br2.readLine();
ps2.println(st);
}
}
}

(NOTE:- If anyone facing any problem regarding the above concept and codes then
feel free to ask me questions. Give positive feedback if you really liked the article.
Give negative feedback as well to make the above concept well explained further.
No concept should be left unexplained. Thank you

Das könnte Ihnen auch gefallen