Anda di halaman 1dari 6

JAVA - NETWORKING

http://www.tutorialspoint.com/java/java_networking.htm

Copyright tutorials point.com

The t erm network programming refers t o writ ing programs t hat execut e across mult iple devices
(comput ers), in which t he devices are all connect ed t o each ot her using a net work.
The java.net package of t he J2SE APIs cont ains a collect ion of classes and int erfaces t hat provide
t he low-level communicat ion det ails, allowing you t o writ e programs t hat focus on solving t he
problem at hand.
The java.net package provides support for t he t wo common net work prot ocols:
T CP: TCP st ands for Transmission Cont rol Prot ocol, which allows for reliable communicat ion
bet ween t wo applicat ions. TCP is t ypically used over t he Int ernet Prot ocol, which is referred t o
as TCP/IP.
UDP: UDP st ands for User Dat agram Prot ocol, a connect ion-less prot ocol t hat allows for
packet s of dat a t o be t ransmit t ed bet ween applicat ions.
This t ut orial gives good underst anding on t he following t wo subject s:
So cket Pro gramming: This is most widely used concept in Net working and it has been
explained in very det ail.
URL Pro cessing: This would be covered separat ely. Click here t o learn about URL Processing
in Java language.

Socket Programming:
Socket s provide t he communicat ion mechanism bet ween t wo comput ers using TCP. A client
program creat es a socket on it s end of t he communicat ion and at t empt s t o connect t hat socket t o
a server.
When t he connect ion is made, t he server creat es a socket object on it s end of t he communicat ion.
The client and server can now communicat e by writ ing t o and reading from t he socket .
The java.net .Socket class represent s a socket , and t he java.net .ServerSocket class provides a
mechanism for t he server program t o list en for client s and est ablish connect ions wit h t hem.
The following st eps occur when est ablishing a TCP connect ion bet ween t wo comput ers using
socket s:
The server inst ant iat es a ServerSocket object , denot ing which port number communicat ion is
t o occur on.
The server invokes t he accept () met hod of t he ServerSocket class. This met hod wait s unt il a
client connect s t o t he server on t he given port .
Aft er t he server is wait ing, a client inst ant iat es a Socket object , specifying t he server name
and port number t o connect t o.
The const ruct or of t he Socket class at t empt s t o connect t he client t o t he specified server
and port number. If communicat ion is est ablished, t he client now has a Socket object capable
of communicat ing wit h t he server.
On t he server side, t he accept () met hod ret urns a reference t o a new socket on t he server
t hat is connect ed t o t he client 's socket .
Aft er t he connect ions are est ablished, communicat ion can occur using I/O st reams. Each socket has
bot h an Out put St ream and an Input St ream. The client 's Out put St ream is connect ed t o t he server's
Input St ream, and t he client 's Input St ream is connect ed t o t he server's Out put St ream.
TCP is a t woway communicat ion prot ocol, so dat a can be sent across bot h st reams at t he same
t ime. There are following usefull classes providing complet e set of met hods t o implement socket s.

ServerSocket Class Met hods:


The java.net.ServerSo cket class is used by server applicat ions t o obt ain a port and list en for
client request s
The ServerSocket class has four const ruct ors:
SN
1

Metho ds with Descriptio n


public ServerSo cket(int po rt) thro ws IOExceptio n
At t empt s t o creat e a server socket bound t o t he specified port . An except ion occurs if t he
port is already bound by anot her applicat ion.

public ServerSo cket(int po rt, int backlo g) thro ws IOExceptio n


Similar t o t he previous const ruct or, t he backlog paramet er specifies how many incoming
client s t o st ore in a wait queue.

public ServerSo cket(int po rt, int backlo g, InetAddress address) thro ws


IOExceptio n
Similar t o t he previous const ruct or, t he Inet Address paramet er specifies t he local IP address
t o bind t o. The Inet Address is used for servers t hat may have mult iple IP addresses, allowing
t he server t o specify which of it s IP addresses t o accept client request s on

public ServerSo cket() thro ws IOExceptio n


Creat es an unbound server socket . When using t his const ruct or, use t he bind() met hod when
you are ready t o bind t he server socket

If t he ServerSocket const ruct or does not t hrow an except ion, it means t hat your applicat ion has
successfully bound t o t he specified port and is ready for client request s.
Here are some of t he common met hods of t he ServerSocket class:
SN
1

Metho ds with Descriptio n


public int getLo calPo rt()
Ret urns t he port t hat t he server socket is list ening on. This met hod is useful if you passed in
0 as t he port number in a const ruct or and let t he server find a port for you.

public So cket accept() thro ws IOExceptio n


Wait s for an incoming client . This met hod blocks unt il eit her a client connect s t o t he server
on t he specified port or t he socket t imes out , assuming t hat t he t ime-out value has been
set using t he set SoTimeout () met hod. Ot herwise, t his met hod blocks indefinit ely

public vo id setSo T imeo ut(int timeo ut)


Set s t he t ime-out value for how long t he server socket wait s for a client during t he accept ().

public vo id bind(So cketAddress ho st, int backlo g)


Binds t he socket t o t he specified server and port in t he Socket Address object . Use t his
met hod if you inst ant iat ed t he ServerSocket using t he no-argument const ruct or.

When t he ServerSocket invokes accept (), t he met hod does not ret urn unt il a client connect s. Aft er
a client does connect , t he ServerSocket creat es a new Socket on an unspecified port and ret urns a
reference t o t his new Socket . A TCP connect ion now exist s bet ween t he client and server, and
communicat ion can begin.

Socket Class Met hods:


The java.net.So cket class represent s t he socket t hat bot h t he client and server use t o
communicat e wit h each ot her. The client obt ains a Socket object by inst ant iat ing one, whereas t he
server obt ains a Socket object from t he ret urn value of t he accept () met hod.
The Socket class has five const ruct ors t hat a client uses t o connect t o a server:
SN
1

Metho ds with Descriptio n


public So cket(String ho st, int po rt) thro ws Unkno wnHo stExceptio n,
IOExceptio n.
This met hod at t empt s t o connect t o t he specified server at t he specified port . If t his
const ruct or does not t hrow an except ion, t he connect ion is successful and t he client is
connect ed t o t he server.

public So cket(InetAddress ho st, int po rt) thro ws IOExceptio n


This met hod is ident ical t o t he previous const ruct or, except t hat t he host is denot ed by an
Inet Address object .

public So cket(String ho st, int po rt, InetAddress lo calAddress, int lo calPo rt)
thro ws IOExceptio n.
Connect s t o t he specified host and port , creat ing a socket on t he local host at t he
specified address and port .

public So cket(InetAddress ho st, int po rt, InetAddress lo calAddress, int


lo calPo rt) thro ws IOExceptio n.
This met hod is ident ical t o t he previous const ruct or, except t hat t he host is denot ed by an
Inet Address object inst ead of a St ring

public So cket()
Creat es an unconnect ed socket . Use t he connect () met hod t o connect t his socket t o a
server.

When t he Socket const ruct or ret urns, it does not simply inst ant iat e a Socket object but it act ually
at t empt s t o connect t o t he specified server and port .
Some met hods of int erest in t he Socket class are list ed here. Not ice t hat bot h t he client and server
have a Socket object , so t hese met hods can be invoked by bot h t he client and server.
SN
1

Metho ds with Descriptio n


public vo id co nnect(So cketAddress ho st, int timeo ut) thro ws IOExceptio n
This met hod connect s t he socket t o t he specified host . This met hod is needed only when
you inst ant iat ed t he Socket using t he no-argument const ruct or.

public InetAddress getInetAddress()


This met hod ret urns t he address of t he ot her comput er t hat t his socket is connect ed t o.

public int getPo rt()


Ret urns t he port t he socket is bound t o on t he remot e machine.

public int getLo calPo rt()


Ret urns t he port t he socket is bound t o on t he local machine.

public So cketAddress getRemo teSo cketAddress()


Ret urns t he address of t he remot e socket .

public InputStream getInputStream() thro ws IOExceptio n


Ret urns t he input st ream of t he socket . The input st ream is connect ed t o t he out put
st ream of t he remot e socket .

public OutputStream getOutputStream() thro ws IOExceptio n


Ret urns t he out put st ream of t he socket . The out put st ream is connect ed t o t he input
st ream of t he remot e socket

public vo id clo se() thro ws IOExceptio n


Closes t he socket , which makes t his Socket object no longer capable of connect ing again t o
any server

Inet Address Class Met hods:


This class represent s an Int ernet Prot ocol (IP) address. Here are following usefull met hods which you
would need while doing socket programming:
SN
1

Metho ds with Descriptio n


static InetAddress getByAddress(byte[] addr)
Ret urns an Inet Address object given t he raw IP address .

static InetAddress getByAddress(String ho st, byte[] addr)


Creat e an Inet Address based on t he provided host name and IP address.

static InetAddress getByName(String ho st)


Det ermines t he IP address of a host , given t he host 's name.

String getHo stAddress()


Ret urns t he IP address st ring in t ext ual present at ion.

String getHo stName()

Get s t he host name for t his IP address.


6

static InetAddress InetAddress getLo calHo st()


Ret urns t he local host .

String to String()
Convert s t his IP address t o a St ring.

Socket Client Example:


The following Greet ingClient is a client program t hat connect s t o a server by using a socket and
sends a greet ing, and t hen wait s for a response.
// File Name GreetingClient.java
import java.net.*;
import java.io.*;
public class GreetingClient
{
public static void main(String [] args)
{
String serverName = args[0];
int port = Integer.parseInt(args[1]);
try
{
System.out.println("Connecting to " + serverName
+ " on port " + port);
Socket client = new Socket(serverName, port);
System.out.println("Just connected to "
+ client.getRemoteSocketAddress());
OutputStream outToServer = client.getOutputStream();
DataOutputStream out =
new DataOutputStream(outToServer);
out.writeUTF("Hello from "
+ client.getLocalSocketAddress());
InputStream inFromServer = client.getInputStream();
DataInputStream in =
new DataInputStream(inFromServer);
System.out.println("Server says " + in.readUTF());
client.close();
}catch(IOException e)
{
e.printStackTrace();
}
}
}

Socket Server Example:


The following Greet ingServer program is an example of a server applicat ion t hat uses t he Socket
class t o list en for client s on a port number specified by a command-line argument :
// File Name GreetingServer.java
import java.net.*;
import java.io.*;
public class GreetingServer extends Thread
{
private ServerSocket serverSocket;
public GreetingServer(int port) throws IOException

{
serverSocket = new ServerSocket(port);
serverSocket.setSoTimeout(10000);
}
public void run()
{
while(true)
{
try
{
System.out.println("Waiting for client on port " +
serverSocket.getLocalPort() + "...");
Socket server = serverSocket.accept();
System.out.println("Just connected to "
+ server.getRemoteSocketAddress());
DataInputStream in =
new DataInputStream(server.getInputStream());
System.out.println(in.readUTF());
DataOutputStream out =
new DataOutputStream(server.getOutputStream());
out.writeUTF("Thank you for connecting to "
+ server.getLocalSocketAddress() + "\nGoodbye!");
server.close();
}catch(SocketTimeoutException s)
{
System.out.println("Socket timed out!");
break;
}catch(IOException e)
{
e.printStackTrace();
break;
}
}
}
public static void main(String [] args)
{
int port = Integer.parseInt(args[0]);
try
{
Thread t = new GreetingServer(port);
t.start();
}catch(IOException e)
{
e.printStackTrace();
}
}
}

Compile client and server and t hen st art server as follows:


$ java GreetingServer 6066
Waiting for client on port 6066...

Check client program as follows:


$ java GreetingClient localhost 6066
Connecting to localhost on port 6066
Just connected to localhost/127.0.0.1:6066
Server says Thank you for connecting to /127.0.0.1:6066
Goodbye!

Anda mungkin juga menyukai