100% found this document useful (1 vote)
294 views

Networking in Java

5.2.2004 introduction to network Facilities Data transformation Synchro, recovery Reliability, multiplex Routing Error / flow control. L A Port is a 16-bit number that identifies an application in a remote machine. Use ports 1024-65,535 for your own applications.

Uploaded by

Vishal Dhamaande
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
294 views

Networking in Java

5.2.2004 introduction to network Facilities Data transformation Synchro, recovery Reliability, multiplex Routing Error / flow control. L A Port is a 16-bit number that identifies an application in a remote machine. Use ports 1024-65,535 for your own applications.

Uploaded by

Vishal Dhamaande
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 43

Networking in Java

Rodrigo García García


[email protected]
http://lgl.epfl.ch

Software Engineering Lab


Swiss Federal Institute of Technology Lausanne
Switzerland

5.2.2004
Introduction to Networking

Facilities Application
Application HTTP,
HTTP,FTP…
FTP…
Data transformation Presentation
Presentation SSL, XDR…
Synchro, recovery Session
Session RPC, RMI…
Reliability, multiplex Transport
Transport TCP,
TCP,UDPUDP
Routing Network
Network IP,
IP,ICMP
ICMP
Error/flow control Link
Link HDLC,
HDLC,LLC…
LLC…
Connectors, volts, wires Physical
Physical RJ45,
RJ45,RS232…
RS232…

OSI Model Internet Protocols

© Rodrigo García García, EPFL - slide 2 - 2/6/2004


Transport protocols
There are two widely used transport Internet protocols:

l TCP (Transmission Control Protocol)


• Connection oriented.
• Reliable
• Error and flow control.
• Order guaranteed.
• Delivery guaranteed.

l UDP (User Datagram Protocol)


• Connectionless. Packet (datagram) based.
• Not reliable
• Losses, duplicates…
• Order of arrival not guaranteed.
• Delivery not guaranteed.

© Rodrigo García García, EPFL - slide 3 - 2/6/2004


Ports
l One machine one address, but several applications:
• How to distinguish different connections?

l A Port is a 16-bit number that identifies an application


in a remote machine.

l Standardized ports reserved for some applications:


• HTTP (port 80)
• Echo (port 7)
• Daytime (port 13)
• …

l Use ports 1024-65,535 for your own applications


• Administrator privileges are required for working with ports in
the range 0-1023.

© Rodrigo García García, EPFL - slide 4 - 2/6/2004


Introduction to Sockets in Java
l A Socket is an end point of a communication link
• Determined by local and remote host address and port.
• Stream based, duplex communication over TCP.

l How to program with sockets:


• Server side
• Create a server socket and bind it to a “well-known” port.
• Listen for incoming clients.
• Upon acceptance, create a normal socket for each client.
• Get output and input streams from the socket.
• Communicate with the client through the streams from the socket.
• Close the socket.
• Client side
• Create a normal socket in any available local port.
• Connect it to the remote server (in Java, this is done at creation).
• Communicate with the server through streams from the socket.
• Close the socket.

© Rodrigo García García, EPFL - slide 5 - 2/6/2004


Socket Programming

Duplex communication

Socket
Known Socket Port Client
Server port Server
accept
Socket

connect

© Rodrigo García García, EPFL - slide 6 - 2/6/2004


Sockets in Java: Server Side (I)
import java.net.*;
import java.io.*; 1.- Import network, input/output and application dependent classes.
import java.util.Date;

public class DateServer {


public static void main(String[] args) throws IOException {
ServerSocket serverSocket = null;
try { 2.- Create a server socket in a “well-known” port.
serverSocket = new ServerSocket(1313);
} catch (IOException e) {
System.err.println("Could not listen on port: 1313.");
System.exit(1);
}

Socket clientSocket = null;


try { 3.- Create a new client socket upon acceptance.
clientSocket = serverSocket.accept();
} catch (IOException e) {
System.err.println("Accept failed.");
System.exit(1);
}
...

© Rodrigo García García, EPFL - slide 7 - 2/6/2004


Sockets in Java: Server Side (II)
...

ObjectOutputStream dateOut = null;


dateOut = new ObjectOutputStream 4.- Get a stream from the socket and
(clientSocket.getOutputStream()); send answer to the client.
dateOut.writeObject(new Date());

dateOut.close();
clientSocket.close(); 5.- Close streams and sockets used.
serverSocket.close();
}
}

- Note: Full objects can be sent through the streams, but they must be Serializable.

© Rodrigo García García, EPFL - slide 8 - 2/6/2004


Sockets in Java: Client Side (I)
import java.io.*;
import java.net.*; 1.- Import network, input/output and application dependent classes.
import java.util.Date;

public class DateClient {


public static void main(String[] args) throws IOException {
Socket dateSocket = null;
ObjectInputStream dateIn = null; 2.- Create a client socket
connected to the right
try { server and port and
dateSocket = new Socket("localhost", 1313);
get a stream from it.
dateIn = new ObjectInputStream(dateSocket.getInputStream());
} catch (UnknownHostException e) {
System.err.println("Server 'localhost' is unknown.");
System.exit(1);
} catch (IOException e) {
System.err.println("Error during connection to 'localhost'.");
System.exit(1);
}
...

© Rodrigo García García, EPFL - slide 9 - 2/6/2004


Sockets in Java: Client Side (II)
...

try {
Date serverDate = (Date) dateIn.readObject(); 3.- Read and print the
System.out.println ("Current server time: " + serverDate); answer from the server.
} catch (ClassNotFoundException e) {
System.err.println ("Not a Date object returned.");
System.exit(1);
}

dateIn.close();
4.- Close streams and sockets used.
dateSocket.close();
}
}

“Current server time: Thu Feb 05 14:45:00 CET 2004”

© Rodrigo García García, EPFL - slide 10 - 2/6/2004


Introduction to Datagrams in Java
l A datagram is an independent message:
• Contains origin and destination addresses and ports.
• Packet-based communication over UDP.

l How to program with datagrams:


• Server side
• Create a datagram socket in a “well-known” port.
• Create an empty datagram packet.
• Link the datagram to the socket and wait for client messages.
• Get client data, address and port and send an answer.
• Client side
• Create a datagram socket in any available port.
• Create a datagram packet with destination address and port.
• Send the datagram through the socket.
• Create an empty packet as a placeholder for the server answer.
• Link the packet to the socket and wait for the server response.
• Get data from the datagram packet and process it.

© Rodrigo García García, EPFL - slide 11 - 2/6/2004


Datagram Programming

Known Datagram Network


Network Datagram
Server port socket socket
Port Client

© Rodrigo García García, EPFL - slide 12 - 2/6/2004


Datagrams in Java: Server Side (I)

import java.io.*;
import java.net.*; 1.- Import network, input/output and application dependent classes.
import java.util.Date;

public class DateServer {


public static void main(String args[]) throws IOException {
DatagramSocket socket = null;
2.- Create a datagram socket in a “well-known port.
socket = new DatagramSocket(1313);

for (int i = 0; i < 10; i++) {


byte[] buf = new byte[256]; 3.- Empty packet.
DatagramPacket packet = new DatagramPacket(buf, buf.length);

socket.receive(packet); 4.- Wait for clients to fill the empty packet.

...

© Rodrigo García García, EPFL - slide 13 - 2/6/2004


Datagrams in Java: Server Side (II)
...

buf = new Date().toString().getBytes(); 5.- Prepare the response.

InetAddress address = packet.getAddress(); 6.- Get client address and port.


int port = packet.getPort();
packet = new DatagramPacket(buf, buf.length, address, port); 7.- Send answer.
socket.send(packet);
} // end for loop.

socket.close(); 8.- Close the socket.


}
}

© Rodrigo García García, EPFL - slide 14 - 2/6/2004


Datagrams in Java: Client Side (I)
import java.io.*;
import java.net.*; 1.- Import network, input/output and application dependent classes.
import java.util.Date;

public class DateClient {


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

DatagramSocket socket = new DatagramSocket(); 2.- Create a datagram socket in an available port

for (int i = 0; i < 10; i++) {


byte[] buf = new byte[256];
3.- Send an
InetAddress address = InetAddress.getByName("localhost");
empty packet
DatagramPacket packet = new DatagramPacket(buf, buf.length, address, 1313);
to the server.
socket.send(packet);

packet = new DatagramPacket(buf, buf.length); 4.- Wait for the server answer.
socket.receive(packet);

...

© Rodrigo García García, EPFL - slide 15 - 2/6/2004


Datagrams in Java: Client Side (II)
...

String received = new String(packet.getData()); 5.- Get server response and print it.
System.out.println("Current server time: " + received);
Thread.sleep(1500);
} //end for loop.

socket.close(); 6.- Close the socket.


}
}

© Rodrigo García García, EPFL - slide 16 - 2/6/2004


Introduction to Multicast
l Multicast is a datagram-based service to broadcast
messages to multiple clients.
• Clients must subscribe to a multicast group.

l How to program with Multicast:


• Server side
• Create a datagram socket in any available port.
• Create a datagram packet with the information to broadcast..
• Send the packet to a class D (multicast) address and known port:
– Multicast addresses range: 224.0.0.0 - 239.255.255.255.
• Client side
• Create a multicast socket with the service port.
• Join the multicast group.
• Create a packet for receiving messages from the group.
• Leave the group.

l Warning:
• Multicast messages are filtered by many routers.
• Even if not filtered, they have a TTL (Time To Live).

© Rodrigo García García, EPFL - slide 17 - 2/6/2004


Multicast Programming

Msocket Port Client

Network
Network
Group: join
send Address
Server Port Dsocket
+
Port Msocket Port Client

receive

Msocket Port Client

© Rodrigo García García, EPFL - slide 18 - 2/6/2004


Multicast in Java: Server Side
import java.io.*;
import java.net.*; 1.- Import network, input/output and application dependent classes.
import java.util.Date;

public class MulticastDateServer {


public static void main(String args[]) throws IOException, InterruptedException {
DatagramSocket socket = new DatagramSocket(5050); 2.- Create socket in an available port.

for (int i = 0; i < 10; i++) {


byte[] buf = new Date().toString().getBytes(); 3.- Prepare data to send.

InetAddress group = InetAddress.getByName("230.0.0.1");


4.- Send a packet to the
DatagramPacket packet;
multicast group address
packet = new DatagramPacket(buf, buf.length, group, 1313);
and port.
socket.send(packet);

Thread.sleep(1500);
}

socket.close(); 5.- Close the socket.


}
}

© Rodrigo García García, EPFL - slide 19 - 2/6/2004


Multicast in Java: Client Side
import java.io.*;
import java.net.*; 1.- Import network, input/output and application dependent classes.
import java.util.Date;

public class MulticastDateClient {


public static void main(String[] args) throws IOException {
MulticastSocket socket = new MulticastSocket(1313);
2.- Create a multicast socket
InetAddress group = InetAddress.getByName("230.0.0.1");
and join the group.
socket.joinGroup(group);

for (int i = 0; i < 10; i++) {


byte[] buf = new byte[256];
3.- Empty packet to
DatagramPacket packet = new DatagramPacket(buf, buf.length);
receive group data.
socket.receive(packet);

String received = new String(packet.getData());


4.- Print the answer.
System.out.println("Current server time: " + received);
}

socket.leaveGroup(group);
5.- Leave the group and close the socket.
socket.close();
}
}

© Rodrigo García García, EPFL - slide 20 - 2/6/2004


Multiple Clients without Multicast (I)
l Many applications require a server to maintain multiple
connections simultaneously.
l The solution is multithreading:
import java.net.*;
import java.io.*; 1.- Import network, input/output and application dependent classes.
import java.util.Date;

public class MultipleDateServer {


public static void main(String[] args) throws IOException {
ServerSocket serverSocket = new ServerSocket(1313); 2.- Create a server socket
in a known port.
ClientAttender attender;
for (int i = 0; i < 10; i++) {
attender = new ClientAttender(serverSocket.accept()); 3.- Create a new thread and
attender.start(); start it on acceptance.
}

serverSocket.close(); 4.- The server socket is closed after attending 10 clients.


}
}
...

© Rodrigo García García, EPFL - slide 21 - 2/6/2004


Multiple Clients without Multicast (II)
...

class ClientAttender extends Thread {


Socket clientSocket;
ObjectOutputStream dateOut;

public ClientAttender(Socket cs) {


clientSocket = cs; 5.- A reference to the socket created in accept() is kept.
}

public void run() {


try {
dateOut = new ObjectOutputStream
(clientSocket.getOutputStream()); 6.- Get an output stream from the socket,
dateOut.writeObject(new Date()); send the object and then
dateOut.close(); close the stream and the socket
clientSocket.close();
} catch (IOException ioe) {
System.err.println("Error writing to the socket");
}
}
}

© Rodrigo García García, EPFL - slide 22 - 2/6/2004


Multiple clients programming

socket Client

Main
Serversocket
Thread

new
socket
Server Thread
socket Client

new
socket
Thread

new
socket
Thread
socket Client

© Rodrigo García García, EPFL - slide 23 - 2/6/2004


Java NIO
l New classes for input/output (since JDK 1.4).

l Allow:
• File locking: useful when sharing files.
• Regular Expressions: pattern recognition.
• Buffer Views: ways to interprete byte buffers.
• Byte Swabbing: big-little endianness.
• Direct Buffers: access to native memmory.
• Memmory-mapped files: map and share files in RAM.
• Scattering Reads and Gathering Writes: compose buffers.
• Direct Channel Transfers: data transfers (DMA).
• Non-blocking sockets:
• Contrary to traditional java.io.
• Multiplexed I/O:
• Multiple clients without need of multithreading.

© Rodrigo García García, EPFL - slide 24 - 2/6/2004


Concepts in Java NIO
l Buffers
• Containers of data.

l Channels
• Data carriers:
• File channels.
• Pipe channels.
• Socket channels.

l Selector
• Multiplexer of registered channels.
• Select the channels which needs processing.

l Key
• Relationship between a selector and a channel.
• Operations of interest.
• Ready operations.

© Rodrigo García García, EPFL - slide 25 - 2/6/2004


Concepts in Java NIO (UML)
Selector
Selector is registered Channel
Channel
* *

SelectionKey
SelectionKey

1 1

{subset}

Operation
Operation
interest ready
* *

© Rodrigo García García, EPFL - slide 26 - 2/6/2004


Programming with Java NIO
l Create a Channel.

l Register it to a Selector.
• Mark the operations of interest to detect in the channel.

l Call to the select operation of Selector.


• Returns a number of the keys whose ready set has changed.

l Get the selected keys:


• Check ready operations for each key.
• Do appropriate processing.
• Remove the key from the selected keys set.
• That clears the ready operations set of the key.

l Recall select operation.

© Rodrigo García García, EPFL - slide 27 - 2/6/2004


Java NIO: Server Side (I)
import java.io.*;
import java.net.*;
import java.nio.*; 1.- Import network, input/output and application dependent classes.
import java.nio.channels.*;
import java.util.*;

public class DateServerNIO {


static final int port = 1313;

void process() throws IOException {


ServerSocketChannel serverChannel = ServerSocketChannel.open();
2.- Create a server socket channel
serverChannel.socket().bind(new InetSocketAddress(port));
and bind it to a known port.
System.out.println("Socket bound");

Selector mux = Selector.open();


serverChannel.configureBlocking(false); 3.- Register the channel in a selector.
serverChannel.register(mux, SelectionKey.OP_ACCEPT);
System.out.println("Channel registered");

...

© Rodrigo García García, EPFL - slide 28 - 2/6/2004


Java NIO: Server Side (II)
while (mux.select() > 0) {
Iterator keyIt = mux.selectedKeys().iterator();
4.- Iterate over the selected keys.

while (keyIt.hasNext()) {
SelectionKey key = (SelectionKey) keyIt.next();
if (key.isAcceptable()) {
ServerSocketChannel server =
(ServerSocketChannel) key.channel();
5.-The server socket is ready for accept.
SocketChannel channel = server.accept();

if (channel != null) {
// channel.configureBlocking(false);
6’.- Register the new channel.
// channel.register (mux, SelectionKey.OP_READ);
ObjectOutputStream dateOut =
new ObjectOutputStream
6.- Send the date.
(Channels.newOutputStream (channel));
dateOut.writeObject(new Date());
}
}
keyIt.remove();
}
}

© Rodrigo García García, EPFL - slide 29 - 2/6/2004


Java NIO: Server Side (III)
...

} //end of process

public static void main(String args[]) {


try{
new DateServerNIO().process();
} catch (IOException ioe) { 1.- Start the server.
ioe.printStackTrace ();
}
}
}

© Rodrigo García García, EPFL - slide 30 - 2/6/2004


RMI

Communicating with
Remote Objects
in Java
RMI (Remote Method Invocation)
l RMI purpose is to make calls to remote objects as if
they were local objects (higher level abstraction
compared to sockets).

l The idea is not new:


• RPC (Remote Procedure Call).
• CORBA (Common Object Request Broker Architecture).
• DCOM (Distributed Component Object Model).
• Web Services.

l RMI is limited to Java programs.


• New extensions for interoperability with CORBA (RMI-IIOP).

l RMI allows dynamic code loading.


• Automatically extends the behavior of an application.

© Rodrigo García García, EPFL - slide 32 - 2/6/2004


Introduction to RMI
l Design and implement the distributed components:
• Define the remote interfaces.
• Implement the remote objects.
• Implement the clients.

l Compile sources and create stubs:


• Compile sources with “javac”.
• Generate stubs with “rmic”.

l Make classes accessible from the network:


• Code to be downloaded must be available.
• Use a web server if dynamic code downloading is needed.

l Start the application:


• Start the RMI registry.
• Start the server.
• Start the clients.

© Rodrigo García García, EPFL - slide 33 - 2/6/2004


Programming with RMI
Client Server

lookup RMI
RMIregistry
registry
Client
Clientapplication
application rebind
Remote
Interface
Local call Remote
Remote
Remote call Object
Object

Remote
RemoteObject
Object
Stub
Stub
rmic
Web
WebServer
Server
download
Remote
RemoteObject
Object
Stub
Stub

Network

© Rodrigo García García, EPFL - slide 34 - 2/6/2004


Designing the remote Interface
l Extends the interface java.rmi.Remote.
l Its procedures can fail due to connection problems:
• They are declared to throw java.rmi.RemoteException.

import java.rmi.Remote;
import java.rmi.RemoteException;

public interface DateService extends Remote {


Date getCurrentDate() throws RemoteException;
}

© Rodrigo García García, EPFL - slide 35 - 2/6/2004


Implementing the Remote Object
l The Remote Object:
• Extends java.rmi.server.UnicastRemoteObject.
• Implements the defined remote interface.

l At server startup:
• Set a Security Manager.
• Set a name for the service, typically:
• “//<hostname>/<service>” or
• “rmi://<hostname>/<service>”
• Bind the name to the RMI registry.
• Exit main routine.

l The Garbage collector does not reclaim the object:


• The RMI registry process keeps a reference to the object.

© Rodrigo García García, EPFL - slide 36 - 2/6/2004


Date Server Implementation (I)
import java.rmi.*;
import java.rmi.server.*; 1.- Import RMI and application dependent classes.
import java.util.Date;

public class DateServer extends UnicastRemoteObject implements DateService {


public DateServer() throws RemoteException { 2.- The constructor of the remote object also throws
super(); RemoteException
}

public Date getCurrentDate() throws RemoteException {


return (new Date()); 3.- Implement the methods of the interface.
}

public static void main(String[] args) {


if (System.getSecurityManager() == null) {
System.setSecurityManager(new RMISecurityManager()); 4.- Install a security manager
}

String registryName = "rmi://localhost/Date";

...

© Rodrigo García García, EPFL - slide 37 - 2/6/2004


Date Server Implementation (II)
try {
DateService dateProvider = new DateServer();
5.- Create the object and bind it
Naming.rebind(registryName, dateProvider);
to a name in the registry.
System.out.println("DateServer bound");
} catch (Exception e) {
System.err.println("DateServer exception: " + e.getMessage());
e.printStackTrace();
}
}
}

© Rodrigo García García, EPFL - slide 38 - 2/6/2004


Implementing the Client
l At startup, the Client:
• Sets up a Security Manager.
• Gets a reference of the remote object.

l To get the reference:


• The client performs a lookup using the registered name.

l During operation
• The client calls the methods of the remote object as usual.
• Note that the client only needs to know the remote interface.

l Notes:
• Remember that remote methods can fail due to problems with
the network connection.
• Minimize network traffic for increasing performance.

© Rodrigo García García, EPFL - slide 39 - 2/6/2004


Date Client Implementation (I)
import java.rmi.*;
1.- Import RMI and application dependent classes.
import java.util.Date;

public class DateClient {


public static void main(String args[]) {
if (System.getSecurityManager() == null) {
System.setSecurityManager(new RMISecurityManager()); 2.- Install a security manager
}

try {
String name = "rmi://localhost/Date";

3.- Get a reference to the remote object.


DateService daytimeServer;
daytimeServer = (DateService) Naming.lookup(name);

System.out.println(daytimeServer.getCurrentDate().toString()); 4.- Call a remote method.


} catch (Exception e) {
System.err.println("DateClient exception: " + e.getMessage());
e.printStackTrace();
}
}
}

© Rodrigo García García, EPFL - slide 40 - 2/6/2004


RMIC
l After compiling the classes, you have to generate the
stub for the server class.

l The stub acts as a proxy class for the client.

l Use “rmic –v1.2 <serverclass>” for programs compiled


with JDK 1.2 or above (recommended).

l The stub generated must be accessible to the client:


• Have a local copy in the client machine.
• Put it under a web server in the server machine.

l Important! When using a web server:


• Make sure that the stub is NOT in the CLASSPATH when
running “rmiregistry”.

© Rodrigo García García, EPFL - slide 41 - 2/6/2004


Java Policy
l The security manager will not let open any port unless
the ones authorized by the policy.

l The policy is a file which describes the right accesses


of external processes to the local machine.
grant {
permission java.net.SocketPermission "*:1024-65535",
"connect,accept";
permission java.net.SocketPermission "*:80", "connect";
};

l The policy above grants access to all ports above 1023


and “connect” access to port 80 (HTTP). This is useful
for downloading code when using a web server.

© Rodrigo García García, EPFL - slide 42 - 2/6/2004


Starting the Application
l Starting the RMI registry:
• “start rmiregistry [port]” (Windows).
• “rmiregistry [port] &” (UNIX).

l Starting the server:


• “java -Djava.security.policy=java.policy DateServer”.

l Starting the client:


• “java -Djava.security.policy=java.policy DateClient”.

l When using a web server, specify also:


• Codebase:
• “-Djava.rmi.server.codebase=http://host:port/webfolder/”
• Hostname:
• “-Djava.rmi.server.hostname=lglpc31.epfl.ch”
• There is a simple HTTP server in Sun’s RMI tutorial.
• ClassFileServer.

© Rodrigo García García, EPFL - slide 43 - 2/6/2004

You might also like