network programming in java
play

Network Programming in Java Agenda Socket-based communication - PowerPoint PPT Presentation

Network Programming in Java Agenda Socket-based communication Remote method invocation (RMI) 1 2 Distributed computations Communication Todays computing environments are Java provides two mechanisms for distributed computing:


  1. Network Programming in Java Agenda • Socket-based communication • Remote method invocation (RMI) 1 2 Distributed computations Communication Today’s computing environments are Java provides two mechanisms for distributed computing: distributed : computations take place on (1) Socket-based communication ( java.net ) different network hosts Sockets are the endpoints of two-way connections between two distributed components that communicate heterogeneous : the hosts can be running with each other. different operating systems (2) Remote method invocation (RMI) ( java.rmi ) RMI allows distributed components to be manipulated (almost) as if they were all on the same host. 3 4

  2. Socket-based Ports communication A server socket listens at a specific port . Sockets are the end points of connections between two hosts and can be used to send and receive data. A port is positive integer less than or equal to 65565. There are two kinds of sockets: server sockets and client The port number is necessary to distinguish different server sockets . applications running on the same host. A server socket waits for requests from clients. Ports 1 through 1023 are reserved for administrative purposes A client socket can be used to send and receive data. (e.g., 21 for FTP, 22 for SSH and SFTP, 23 for Telnet, 25 for e-mail, and 80 for HTTP). 5 6 Server sockets Methods of ServerSocket A server socket is an instance of the ServerSocket class and Socket accept() can be created by one of these constructors: Waits for a connection request. The thread that ServerSocket(int port) executes the method will be blocked until a request is ServerSocket(int port, int backlog) received, at which time the method returns a client socket. port : port number at which the server will be void close() listening for requests from clients. Stops waiting for requests from clients. backlog : the maximum length of the queue of clients waiting to be processed (default is 50). Server sockets can be created only with Java applications, not applets. 7 8

  3. Client sockets Typical use of ServerSocket A client socket is an instance of the Socket class and can be obtained in two ways: try { ServerSocket s = new ServerSocket(port); while (true) { (1) On the server side as return value of the accept() Socket incoming = s.accept(); method. «Handle a client» incoming.close(); (2) On the client side by using the constructor } s.close(); } catch (IOException e) { Socket(String host, int port) «Handle exception» } host : the address of the host port : the port number 9 10 Clients’ communication with a server Methods of Socket new Socket(...) ServerSocket ServerSocket Server application getInputStream() Client Returns an InputStream object for receiving data Socket Socket getOutputStream() Returns and OutputStream object for sending data Socket close() Client Closes the socket connection Socket Socket Communication is handled on both sides by Socket objects. 11 12

  4. Typical use of Socket Development of client/server programs try { Socket socket = new Socket(host, port); 1. Decide if it reasonable to implement a server and BufferedReader in = new BufferedReader( one or more matching clients new InputStreamReader( socket.getInputStream() )); PrintWriter out = new PrintWriter( 2. Design a text based communication protocol new OutputStreamWriter( socket.getOutputStream() )); 3. Implement the server «Send and receive data» in.close(); out.close(); 4. Test the server with a telnet program socket.close(); } catch (IOException e) { «Handle exception» 5. Implement and test a Java client } telnet : A terminal emulation program for TCP/IP networks (such as the Internet) 13 14 A simple echo server out.println("Hello! This is the Java EchoServer."); out.println("Enter BYE to exit."); out.flush(); import java.io.*; while (true) { import java.net.*; String str = in.readLine(); if (str == null) public class EchoServer { break; // client closed connection public static void main(String[] args) { out.println("Echo: " + str); try { out.flush(); ServerSocket s = new ServerSocket(8008); if (str.trim().equals("BYE")) while (true) { break; } Socket incoming = s.accept(); BufferedReader in = new BufferedReader( in.close(); out.close(); new InputStreamReader( incoming.close(); incoming.getInputStream())); } PrintWriter out = new PrintWriter( new OutputStreamWriter( } catch (Exception e) {} } incoming.getOutputStream())); } continued 15 16

  5. A simple Java client Testing the server with telnet import java.io.*; import java.net.*; venus% telnet saturn 8008 public class EchoClient { Trying 140.192.34.63 ... public static void main(String[] args) { Connected to saturn. try { Escape character is '^]'. String host = Hello! This is the Java EchoServer. args.length > 0 ? args[0] : " localhost "; Enter BYE to exit. Socket socket = new Socket(host, 8008); Hi, this is from venus BufferedReader in = new BufferedReader( Echo: Hi, this is from venus new InputStreamReader( BYE socket.getInputStream())); Echo: BYE PrintWriter out = new PrintWriter( Connection closed by foreign host. new OutputStreamWriter( socket.getOutputStream())); continued 17 18 Running the Java client // send data to the server for (int i = 1; i <= 10; i++) { System.out.println("Sending: line " + i); out.println("line " + i); venus% java EchoClient saturn out.flush(); Sending: line 1 } Sending: line 2 out.println("BYE"); ... out.flush(); Sending: line 10 Hello! This is Java EchoServer. // receive data from the server Enter BYE to exit. while (true) { Echo: line 1 String str = in.readLine(); Echo: line 2 if (str == null) ... break; Echo: line 10 System.out.println(str); Echo: BYE } in.close(); out.close(); socket.close(); } catch (Exception e) {} } } 19 20

  6. An echo server that handles ClientHandler multiple clients simultaneously public class ClientHandler extends Thread { Use a separate thread for each client. protected Socket incoming; public ClientHandler(Socket incoming) { this.incoming = incoming; public class MultiEchoServer { } public static void main(String[] args) { try { public void run () { ServerSocket s = new ServerSocket(8009); try { while (true) { BufferedReader in = new BufferedReader( Socket incoming = s.accept(); new InputStreamReader( new ClientHandler(incoming).start(); incoming.getInputStream())); } PrintWriter out = new PrintWriter( } catch (Exception e) {} new OutputStreamWriter( } incoming.getOutputStream())); } continued 21 22 Broadcasting messages to clients out.println("Hello! ..."); out.println("Enter BYE to exit."); out.flush(); while (true) { String str = in.readLine(); Development of a chat server that if (str == null) break; out.println("Echo: " + str); out.flush(); • handles multiple clients simultaneously if (str.trim().equals("BYE")) break; } • broadcasts a message received from a client to all in.close(); out.close(); other active clients. incoming.close(); } catch (Exception e) {} } } The server needs to keep track of active clients. 23 24

  7. Chat example ChatServer public class ChatServer { public ChatServer(int port) throws IOException { ServerSocket s = new ServerSocket(port); while (true) new ChatHandler (s.accept()).start(); } public static void main(String[] args) throws IOException { if (args.length != 1) throw new RuntimeException( "Syntax: java ChatServer <port>"); new ChatServer(Integer.parseInt(args[0])); } } 25 26 public void run() { ChatHandler String name = ""; try { name = in.readUTF(); System.out.println("New client " + name + " from " + public class ChatHandler extends Thread { socket.getInetAddress()); Socket socket; broadcast (name + " entered"); DataInputStream in; while(true) DataOutputStream out; broadcast (name + ": " + in.readUTF()); static Set<ChatHandler> handlers = } catch (IOException e) { (Set<ChatHandler>) Collections.synchronizedSet( System.out.println("-- Connection to user lost."); new HashSet<ChatHandler>()); } finally { handlers.remove(this); public ChatHandler(Socket socket) throws IOException { try { this.socket = socket; broadcast (name + " left"); in = new DataInputStream(socket.getInputStream()); in.close(); out = new DataOutputStream(socket.getOutputStream()); out.close(); handlers.add(this); socket.close(); } } catch (IOException e) {} } } continued continued 27 28

Download Presentation
Download Policy: The content available on the website is offered to you 'AS IS' for your personal information and use only. It cannot be commercialized, licensed, or distributed on other websites without prior consent from the author. To download a presentation, simply click this link. If you encounter any difficulties during the download process, it's possible that the publisher has removed the file from their server.

Recommend


More recommend