2. Java Program
Java source di buat
− pakai text editor dan disimpan dengan nama sesuai
nama class (Case Sensitive) dan ekstensi .java
Di compile menghasilkan Byte code dengan
nama sesuai nama class (Case Sensitive) dan
ekstensi .class
− Memerlukan java compiler yang tersedia di JDK
Byte code di jalankan menggunakan JVM
− JVM diperoleh dalam paket JRE atau JDK
3. Client – Server
Bentuk komunikasi menggunakan model client
server
Program yang dibuat harus terdiri dari client
dan server
Server bersifat pasif, program yang menunggu
Client bersifat aktif, program yang
menghubungi server
P2P juga mempunyai client dan server
4. Komunikasi Antar Aplikasi
IPC = Komunikasi antar proses
− Shared memory
− Message Passing di jaringan
Socket
RPC/RMI
Socket dibuat berdasarkan pasangan alamat IP
dan port yang dipakai/dipilih
Alamat IP sering digantikan oleh nama host
port adalah bilangan 1 – 65535 untuk tcp/udp
5. Socket
Socket adalah representasi dari gerbang
komunikasi di jaringan
Socket bekerja layaknya layanan I/O Unix
seperti akses file, pipe dan FIFO.
− fd = fopen --> fd adalah file descriptor
Socket berfungsi untuk:
− Meng establish koneksi, dan
− Menentukan alamat untuk gerbang komunikasi
6. Port
Socket dibuat menggunakan pasangan port
dan ip address
Port untuk transport layer (untuk 1 aplikasi
diperjanjikan 1 port tententu)
− 16 bit --> nilainya 1 – 65535
Ip address network layer
7. Sockets dan Ports
message
agreed port
any port
socketsocket
Internet address = 138.37.88.249Internet address = 138.37.94.248
other ports
client server
Client
creates socket
sends to addr/port
Server
creates socket
binds to port
advertises addr/port
9. Java net API
Socket di Java dibedakan dalam 3 macam:
− Socket client untuk TCP (stream)
java.net.Socket
− Socket server untuk TCP (stream)
java.net.ServerSocket
− Socket datagram untuk UDP
java.net.DatagramSocket
10. Client socket
public Socket(String host, int port) throws
UnknownHostException, IOException
Contoh:
try {
Socket toOReilly = new Socket("www.oreilly.com", 80);
// send and receive data...
}
catch (UnknownHostException ex) {
System.err.println(ex);
}
catch (IOException ex) {
System.err.println(ex);
11. Class SocketAddress dan connect
package java.net.*;
public abstract class SocketAddress {
public SocketAddress( ) {}
}
public SocketAddress getRemoteSocketAddress( )
public SocketAddress getLocalSocketAddress( )
A SocketAddress is necessary to connect an unconnected
socket via the connect( ) method:
public void connect(SocketAddress endpoint) throws IOException
12. Server socket
public ServerSocket(int port) throws
BindException, IOException
public ServerSocket(int port, int queueLength)
throws BindException, IOException
public ServerSocket(int port, int queueLength,
InetAddress bindAddress)
throws IOException
public ServerSocket( ) throws IOException //
Java 1.4
13. Step utk Program Client TCP
Create a Socket object.
− Socket client = new Socket("hostname", portNumber);
Create an output stream that can be used to send information to the Socket.
− PrintWriter out = new PrintWriter(client.getOutputStream(), true);
Create an input stream to read the response from the server.
− InputStreamReader in = new
InputStreamReader(client.getInputStream());
Do I/O with input and output streams.
Close the Socket when done.
− client.close();
14. Program Client untuk TCP
import java.net.*;
import java.io.*;
public class DaytimeClient {
public static void main(String[] args) {
String hostname;
if (args.length > 0) {
hostname = args[0];
}
else {
hostname = "tock.usno.navy.mil";
}
try {
Socket theSocket = new Socket(hostname, 13);
InputStream timeStream = theSocket.getInputStream();
StringBuffer time = new StringBuffer();
15. Program Client untuk TCP
int c;
while ((c = timeStream.read()) != -1) time.append((char) c);
String timeString = time.toString().trim();
System.out.println("It is " + timeString + " at " + hostname);
} // end try
catch (UnknownHostException e) {
System.err.println(e);
}
catch (IOException e) {
System.err.println(e);
}
} // end main
} // end DaytimeClient
16. Step utk Program Server TCP
Create a ServerSocket object.
− ServerSocket listenSocket =
new ServerSocket(portNumber);
Create a Socket object from the ServerSocket
(accept connection)
− Socket server = listenSocket.accept();
Create an input stream to read input from the client
− BufferedReader in = new BufferedReader
(new InputStreamReader(server.getInputStream()));
Create an output stream that can be used to
send information back to the client
− PrintWriter out = new PrintWriter(server.getOutputStream());
Do I/O with input and output streams.
Close the Socket when done.
− server.close();
17. Program Server untuk TCP
import java.net.*;
import java.io.*;
import java.util.Date;
public class DaytimeServer {
public final static int DEFAULT_PORT = 13;
public static void main(String[] args) {
int port = DEFAULT_PORT;
if (args.length > 0) {
try {
port = Integer.parseInt(args[0]);
if (port < 1 || port > 65535) {
System.out.println("Port must between 1 and 65535");
return;
}
}
18. Program Server untuk TCP
catch (NumberFormatException ex) {
// use default port }
}
try {
ServerSocket server = new ServerSocket(port);
Socket connection = null;
while (true) {
try {
connection = server.accept();
Writer out = new
OutputStreamWriter(connection.getOutputStream());
Date now = new Date();
out.write(now.toString() +"rn");
out.flush();
connection.close();
}
19. Program Server untuk TCP
catch (IOException ex) {}
finally {
try {
if (connection != null) connection.close();
}
catch (IOException ex) {}
}
} // end while
} // end try
catch (IOException ex) {
System.err.println(ex);
} // end catch
} // end main
} // end DaytimeServer
20. Client UDP
import java.net.*;
import java.io.*;
public class UDPDiscardClient {
public final static int DEFAULT_PORT = 9;
public static void main(String[] args) {
String hostname;
int port = DEFAULT_PORT;
if (args.length > 0) {
hostname = args[0];
try {
port = Integer.parseInt(args[1]);
}
catch (Exception ex) {
// use default port
}
}
else {
hostname = "localhost";
}
21. Client UDP
try {
InetAddress server = InetAddress.getByName(hostname);
BufferedReader userInput = new BufferedReader(new
InputStreamReader(System.in));
DatagramSocket theSocket = new DatagramSocket();
while (true) {
String theLine = userInput.readLine();
if (theLine.equals(".")) break;
byte[] data = theLine.getBytes();
DatagramPacket theOutput = new DatagramPacket(data,
data.length, server, port);
theSocket.send(theOutput);
} // end while
} catch (UnknownHostException uhex) {
System.err.println(uhex);
} catch (SocketException sex) {
System.err.println(sex);
} catch (IOException ioex) {
System.err.println(ioex); }
} // end main
}
22. Server UDP
import java.net.*;
import java.io.*;
public class UDPDiscardServer {
public final static int DEFAULT_PORT = 9;
public final static int MAX_PACKET_SIZE =
65507;
public static void main(String[] args) {
int port = DEFAULT_PORT;
byte[] buffer = new byte[MAX_PACKET_SIZE];
try {
port = Integer.parseInt(args[0]);
}
catch (Exception ex) {
// use default port
}
23. Server UDP
try {
DatagramSocket server = new DatagramSocket(port);
DatagramPacket packet = new DatagramPacket(buffer,
buffer.length);
while (true) {
try {
server.receive(packet);
String s = new String(packet.getData(), 0,
packet.getLength());
System.out.println(packet.getAddress() + " at
port " + packet.getPort() + " says " + s);
// reset the length for the next packet
packet.setLength(buffer.length);
} catch (IOException ex) {
System.err.println(ex);
}
} // end while
} catch (SocketException ex) {
System.err.println(ex); } // end catch
} // end main
}
33. RPC
avg.x --> interface specification
− Setelah di compile pakai rpcgen, menghasilkan
− avg.h, avg_xdr.c, avg_clnt.c, avg_svc.c
avg_proc.c --> procedure di server
ravg.c --> main program di client
Di compile dengan cara:
− Client: cc -o ravg ravg.c avg_xdr.c avg_clnt.c
− ravg
− Server: cc -o avg_svc avg_proc.c avg_xdr.c avg_svc.c
− avg_svc
39. Running RPC
Menjalankan server:
avg_svc &
menjalankan client:
ravg server 2 3 4 5
hasilnya
value = 2.000000e+00
value = 3.000000e+00
value = 4.000000e+00
value = 5.000000e+00
average = 3.500000e+00
bila berhasil
40. Aplikasi yang menerapkan RPC
NFS (Network File System)
NIS (Network Information System)
− YP (Yellow Pages)
41. Bentuk Komunikasi
Unicast --> TCP
− Satu tujuan
Broadcast --> UDP
− Semua tujuan
− Semua host pada jaringan A, B, dan C akan
menerima
Multicast --> bentuk khusus dari UDP
− Banyak tujuan yang dipilih
− Misal pada jaringan A dipilih 5 dari 20, jaringan B
dipilih 3 dari 10, dan jaringan C dipilih 2 dari 6
− Jumlah hosts dari jaringan A, B, dan C ada 36,
namun yang dipilih hanya 10
42. Multicast socket
Class MulticastSocket merupakan subclass dari
DatagramSocket
public class MulticastSocket extends DatagramSocket
Pemanggilan class tanpa parameter
public MulticastSocket( ) throws SocketException
Pemanggilan class dengan parameter port
public MulticastSocket(int port) throws SocketException
Pemanggilan class dengan parameter SocketAddress
public MulticastSocket(SocketAddress bindAddress) throws
IOException
43. Contoh pemanggilan
try {
MulticastSocket ms = new MulticastSocket( );
// send some datagrams...
}
catch (SocketException se) {
System.err.println(se);
}
try {
MulticastSocket ms = new MulticastSocket(4000);
// receive incoming datagrams...
}
catch (SocketException ex) {
System.err.println(ex);
}
44. Contoh pemanggilan
try {
SocketAddress address = new
InetSocketAddress(4000);
MulticastSocket ms = new MulticastSocket(address);
// receive incoming datagrams...
}
catch (SocketException ex) {
System.err.println(ex);
}
45. Java RMI
Interface --> Fibonacci.java
Class untuk implementasi dari interface
− FibonacciImpl.java
Class untuk register server nya
− FibonacciServer.java
Class untuk client
− FibonacciClient.java
46. Meng compile RMI
Seluruh class di compile dengan cara
javac Fibonacci*.java
Hasil compile dari class Implementasi server
(file .class nya) di compile lagi untuk
menghasilkan skeleton dan stub dengan cara
rmic FibonacciImpl
47. Menjalankan Java RMI
Menjalankan rmiregistry dengan cara
start rmiregistry --> di Windows
atau
rmiregistry & --> di Linux
Menjalankan server dengan cara
java FibonacciServer
Menjalankan client dengan cara
java FibonacciClient rmi://host.com/fibonacci 0 1 2 3 4 5
Hasil outputnya:
The 0th Fibonacci number is 1
The 1th Fibonacci number is 1
The 2th Fibonacci number is 2
The 3th Fibonacci number is 3
The 4th Fibonacci number is 5
The 5th Fibonacci number is 8
48.
Pemrograman berbasis Socket, aplikasi yang dibuat
langsung menggunakan transport (TCP/UDP) -->
layer 4 = identik dengan low level programming
Pemrograman berbasis RPC/RMI, aplikasi yang
dibuat tidak mengakses langsung ke transport
melainkan melalui perantaraan RPC/RMI (layer 5 dan
6) = midle level programming
Pemrograman berbasis Web, aplikasi di buat di atas
aplikasi Web (layer 7) = high level programming
50. Web Programming
Program di jalan kan di Web Browser (di Client)
− Dibuat menggunakan bahasa pemrograman
− Java (Applet) atau bahasa scripting Javascript
Program di jalan kan di Web Server (di Server)
51. Client side program
Program diambil dari server bersama-sama
dengan html nya dan di jalan kan di client
Menggunakan Javascript atau Java Applet
We turn our attention briefly to how programs connect to networks, including how we do it from a program.
Port - the external (network) interface for a program. IP addr and port uniquely identify connect point.
Socket - the internal (OS) interface to the network. Programs send and receive on sockets, but address messages to ports.
Let’s look in detail at an example using UDP.
Both client and server create sockets. The server must somehow make its address available to the client. We’ll discuss how this might be done later.
The client sends a request to the server. This carries the return address. The server responds.
Both processes create a socket and then use it to communicate.
A server can publish its address in a number of different ways:
1) Well known
2) A name server
3) “Word of mouth”
#include &lt;sys/types.h&gt;
#include &lt;sys/socket.h&gt;
#include &lt;netinet/in.h&gt;
#include &lt;netdb.h&gt;
#include &lt;stdio.h&gt;
/*
* Here we send a datagram to a server whose name comes from the
* command line arguments. The form of the command line is
* dgramsend hostname portnumber
* In the included file &lt;netinet/in.h&gt; a sockaddr_in is defined as follows:
* struct sockaddr_in {
* short sin_family; // protocol family, e.g. Inet or Novell
* u_short sin_port; // port number
* struct in_addr sin_addr; // IP address
* char sin_zero[8]; // flags
* };
*/
/*
* Construct name, with no wildcards, of the socket to send to.
* Getnostbyname() returns a structure including the network address
* of the specified host. The port number is taken from the command
* line.
*/
Note the use of sendto() rather than write.
#include &lt;sys/types.h&gt;
#include &lt;sys/socket.h&gt;
#include &lt;netinet/in.h&gt;
#include &lt;stdio.h&gt;
/*
* This program creates a datagram socket, binds a name to it, then
* reads from the socket.
*/
Unlike the client the server must bind its socket to a port to allow the client to connect. This is done by partially filling in the sockaddr_in struct and passing it to bind.
In the top half we now pass the sockaddr_in struct to getsockname and it fills in the port number for us.
We then simply read from the socket. This blocks until some data arrives (as it would with standard input).
We start with three files, source files for the client and server and an interface definition file written in an interface definition language. We first compile the idl file with an idl compiler. This generates both proxies (stubs) and a header file that is then included in the source of the client and server (providing the interface definition).
These files are then all compiled - the header is included by all four source files - to generate object files. The client’s object files are linked with any library, and so are the servers.
What do the proxies do?
Rpc tries to deal with heterogeneous client and server by passing parameters/results in a way that allows them to be accurately reconstructed. This means the interface definition language must have types and it also means that the types passed must be found in/composed of the types of the IDL.
The process at the calling end is call “marshalling”. Note that the client stub must also identify the procedure to be called (“add”). The rpc runtime on the server side will most likely support a number of remote procedures and it must know which one this invocation is destinged for. (The network port number is a well know port for the rpc runtime.)
The server runtime passes the message to the appropriate stub with uses the parameters to make a local call to the procedure.
What if the two machines involved use different representations for the integers? Message uses a standard format (e.g. big endian, little endian or bcd encoding).