Download presentation
Presentation is loading. Please wait.
Published byOsborn Kelly Small Modified over 8 years ago
1
第十一讲 分布式编程 Socket and RMI 李庆旭
2
2 本章内容提要 Socket TCP /IP protocol suit Socket A TCP Server and a TCP Client Supporting Multiple Concurrent Clients A UDP Server and a UDP Client RMI What is RMI? How does RMI work? A RMI Server and a RMI Client How does RMI pass parameters? RMI vs. Socket CORBA Q&A
3
TCP/IP Protocol Suit 3
4
ISO/OSI Reference Model 4 Introduced in 1978, the ISO Open Systems Interconnection (OSI) Reference model describes networking as "a series of protocol layers with a specific set of functions allocated to each layer. Each layer offers specific services to higher layers while shielding these layers from the details of how the services are implemented.
5
TCP/IP Protocol Suit TCP/IP protocol suit is a complete protocol stack with many protocols. TCP: Transmission Control Protocol IP: Internet Protocol UDP: User Datagram Protocol The first implementation of TCP/IP is in BSD Unix 4.x developed by 加州大学伯克利分校 5
6
TCP/IP and OSI Reference Model 6 TCP and UDP are at Transport layer IP is at Network layer
7
Socket 7
8
BSD Socket is the programming interface of the TCP/IP protocol suit implemented in the BSD UNIX 4.x. With BSD Socket, programmers can developed network programs using TCP, UDP and IP protocols. Microsoft Windows also has a Socket implementation called WinSocket. 8
9
Socket (cont.) Java Socket API is implemented with the underlying OS Socket API (e.g. BSD Socket andWinSocket). 9
10
TCP Port To support many concurrent TCP connections, OS needs a way to recognize a specific TCP connection. Each TCP connection is bound to a specific TCP port. A TCP port is an unsigned 16 bits integer. TCP Ports from 0 to1024 are reserved. Well-known TCP ports: HTTP(80),FTP(21), TELNET(23), etc. 10
11
UDP Port To support many concurrent UDP connections, OS needs a way to recognize a specific UDP connection. Each UDP connection is bound to a specific UDP port. A UDP port is an unsigned 16 bits integer. UDP Ports from 0 to1024 are reserved. Famous Protocols using UDP: TFTP, BOOTP, etc. 11
12
Server and Client Normally, a server runs on a specific computer and has a socket that is bound to a specific port number. The server just waits, listening to the socket for a client to make a connection request. On the client-side: The client knows the hostname of the machine on which the server is running and the port number on which the server is listening. 12
13
Server and Client (cont.) First, the server listens on a specific TCP or UDP port. 13
14
Server and Client (cont.) Then, a client tries to make a connection to the server. 14
15
Server and Client (cont.) If everything goes well, the server accepts the connection. 15
16
A TCP Server and a TCP Client 16
17
A TCP Echo Server import java.io.*; import java.net.*; public class TCPEchoServer { public static void main(String[] args ) { try { ServerSocket s = new ServerSocket(7); Socket incoming = s.accept( ); BufferedReader in = new BufferedReader (new InputStreamReader(incoming.getInputStream())); PrintWriter out = new PrintWriter (incoming.getOutputStream(), true /* autoFlush */); 17
18
A TCP Echo Server (cont.) boolean done = false; while (!done) { String line = in.readLine(); if (line == null) done = true; else { System.out.println("Received: " + line); out.println("Echo: " + line); if (line.trim().equals("BYE")) done = true; } incoming.close(); } catch (Exception e) { System.out.println(e); } 18
19
A TCP ECHO Client import java.io.*; import java.net.*; public class TCPEchoClient { public static void main(String[] args) throws IOException { Socket echoSocket = null; PrintWriter out = null; BufferedReader in = null; try { echoSocket = new Socket("localhost", 7); out = new PrintWriter(echoSocket.getOutputStream(), true); in = new BufferedReader(new InputStreamReader( echoSocket.getInputStream())); } catch (UnknownHostException e) { System.err.println("Don't know about host: taranis."); System.exit(1); } catch (IOException e) { System.err.println("Couldn't get I/O for " + "the connection to: taranis."); System.exit(1); } 19
20
A TCP ECHO Client (cont.) BufferedReader stdIn = new BufferedReader( new InputStreamReader(System.in)); String userInput; while ((userInput = stdIn.readLine()) != null) { out.println(userInput); System.out.println(in.readLine()); } out.close(); in.close(); stdIn.close(); echoSocket.close(); } 20
21
Demo Java TCPEchoServer Java TCPEchoClient 21
22
Supporting Multiple Concurrent Clients 22
23
A Multi-threaded TCP Echo Server import java.io.*; import java.net.*; public class ThreadedTCPEchoServer { public static void main(String[] args ) { int i = 1; try { ServerSocket s = new ServerSocket(7); for (;;) { Socket incoming = s.accept( ); System.out.println("Spawning " + i); new ThreadedEchoHandler(incoming, i).start(); i++; } catch (Exception e) { System.out.println(e); } 23
24
A Multi-threaded TCP Echo Server (cont.) class ThreadedEchoHandler extends Thread { public ThreadedEchoHandler(Socket i, int c) { incoming = i; counter = c; } public void run() { try { BufferedReader in = new BufferedReader (new InputStreamReader(incoming.getInputStream())); PrintWriter out = new PrintWriter (incoming.getOutputStream(), true /* autoFlush */); 24
25
A Multi-threaded TCP Echo Server (cont.) boolean done = false; while (!done) { String str = in.readLine(); if (str == null) done = true; else { System.out.println("Received: " + str); out.println("Echo (" + counter + "): " + str); if (str.trim().equals("BYE")) done = true; } incoming.close(); } catch (Exception e) { System.out.println(e); } private Socket incoming; private int counter; } 25
26
Demo Java ThreadedTCPEchoServer Java TCPEchoClient 26
27
A UDP Server and a UDP Client 27
28
A UDP Echo Server import java.io.*; import java.net.*; public class UDPEchoServer { public static void main(String[] args ) { try { DatagramSocket socket = new DatagramSocket(7); boolean done = false; while (!done) { byte[] buf = new byte[256]; DatagramPacket packet = new DatagramPacket(buf, buf.length); socket.receive(packet); 28
29
A UDP Echo Server (cont.) String s= new String(buf); if( s.trim().equals("BYE")) done = true; else { System.out.println("Received: " + s); InetAddress address = packet.getAddress(); int port = packet.getPort(); packet = new DatagramPacket(buf, buf.length, address, port); socket.send(packet); } socket.close(); } catch (Exception e) { System.out.println(e); } 29
30
A UDP Echo Client import java.io.*; import java.net.*; public class UDPEchoClient { public static void main(String[] args) throws IOException { int port; InetAddress address; DatagramSocket socket = null; DatagramPacket packet; byte[] sendBuf = new byte[256]; if (args.length != 1) { System.out.println("Usage: java QuoteClient "); return; } socket = new DatagramSocket(); BufferedReader stdIn = new BufferedReader( new InputStreamReader(System.in)); String userInput; 30
31
A UDP Echo Client (cont.) while ((userInput = stdIn.readLine()) != null) { byte[] buf = userInput.getBytes(); address = InetAddress.getByName(args[0]); packet = new DatagramPacket(buf, buf.length, address, 7); socket.send(packet); packet = new DatagramPacket(buf, buf.length); socket.receive(packet); String received = new String(packet.getData(), 0, packet.getLength()); System.out.println("Received:" + received); } socket.close(); } 31
32
Demo Java UDPEchoServer Java UDPEchoClient localhost 32
33
What is RMI? 33
34
RMI Local Method Invocation Normally, a java program only calls methods of classes whose.class files exist locally (i.e. within a same JVM). JVM dynamically load, verify, link and JIT.class files at run time. Remote Method Invocation RMI enables java programs to call methods whose.class files exist remotely (i.e. Cross JVM). 34
35
How Does RMI Work? 35
36
How does RMI work? 36 Client Class Stub Class JVM Server Class Stub Class JVM TCP Socket over TCP/IP Network Legend Method CallMethod Return
37
How does RMI work? (cont.) From the client’s perspective, calling a remote method is no different from calling a local method. But, the client doesn’t call the remote method directly. Instead, it calls a local method in the Stub Class. The sub class marshals method parameters, then sends a TCP packet over sockets. 37
38
How does RMI work? (cont.) The stub class on the server listens on a TCP socket. After accepting the packet from the client, the stub class on the server side un- marshals method parameters then pass them to the actual server class. The server class executes its method as if it is called by the stub class on the server side. After this method return, this stub class marshals the return value and all parameters, then send a return packet back to the client. 38
39
How does RMI work? (cont.) Then, the stub class on the client receives the result packet and un-marshals it. After that, it returns back to the client class. 39
40
RMI Registry 40
41
RMI Registry RMI Server registers its remote objects into the RMI Registry. RMI Client looks up remote objects from the RMI Registry. 41
42
RMI Registry (cont.) 42 RMI Registry RMI Server RMI Client Object Store Registers remote objectsLooks up remote objects
43
A RMI Server and a RMI Client 43
44
The Interface Implemented by the Server import java.rmi.*; // All remote interfaces must derive from the // Remote interface and throw RemoteException. public interface Product extends Remote { String getDescription(String clientID) throws RemoteException; } 44
45
The Server Implementation Class import java.rmi.*; import java.rmi.server.*; public class ProductImpl extends UnicastRemoteObject implements Product { public ProductImpl(String n) throws RemoteException { name = n; } public String getDescription(String clientID) throws RemoteException { return "Client ID:" + clientID + ".I am a " + name + ". Buy me!"; } private String name; } 45
46
The RMI Server import java.rmi.*; import java.rmi.server.*; import sun.applet.*; public class ProductServer { public static void main(String args[]) { try { System.out.println ("Constructing server implementations..."); ProductImpl p1 = new ProductImpl("Blackwell Toaster"); ProductImpl p2 = new ProductImpl("ZapXpress Microwave Oven"); System.out.println ("Binding server implementations to registry..."); Naming.rebind("toaster", p1); Naming.rebind("microwave", p2); System.out.println ("Waiting for invocations from clients..."); } catch(Exception e) { System.out.println("Error: " + e); } 46
47
The RMI Client import java.rmi.*; import java.rmi.server.*; public class ProductClient { public static void main(String[] args) { System.setSecurityManager(new RMISecurityManager()); String url = "rmi://localhost/"; // change to "rmi://yourserver.com/" // when server runs on remote machine // yourserver.com try { Product c1 = (Product)Naming.lookup(url + "toaster"); Product c2 = (Product)Naming.lookup(url + "microwave"); System.out.println(c1.getDescription("client 1")); System.out.println(c2.getDescription("client 2")); } catch(Exception e) { System.out.println("Error " + e); } System.exit(0); } 47
48
Compile javac *.java rmic ProductImpl 48
49
Run @ECHO OFF start rmiregistry REM start the server start java ProductServer REM wait the server to start Pause REM start the client java -Djava.security.policy=client.policy ProductClient 49
50
Deploy Client Product.class (Interface class) ProductImpl_Stub.class (Stub class) ProductClient.class Client.policy Server Product.class (Interface class) ProductImpl_Stub.class(Stub class) ProductImpl.class (Server Implementation Class) ProductServer.class (Server startup class) 50
51
How does RMI pass parameters? 51
52
How does RMI pass parameters? The stub class on the caller side marshals parameters. Marshaling means serializing parameters into a byte stream. The stub class on the callee side un-marshals parameters. Un-marshaling means de- serializing parameters from the byte stream. So, all the parameters of a remote method must be Serializable.Serializable 52
53
RMI vs. Socket 53
54
RMI vs. Socket RMI Simple to use But, can only connect to Java Programs. For example, cannot connect to C++ programs. Socket Difficult to use Can connect to programs written in other languages only if it supports socket. So, a java client can connect to a C++ server via socket. 54
55
55 Q&A Thanks !
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.