1 / 39

NETWORKING IN JAVA java PACKAGE

NETWORKING IN JAVA java.net PACKAGE. Programming with Sockets Developing a TCP Client Developing a TCP Server Client/Server Applications using UDP Writing a Multithreaded Server Network Application Programming Techniques Multi-Protocol Programming using URLs Passing Java Objects

trang
Télécharger la présentation

NETWORKING IN JAVA java PACKAGE

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. NETWORKING IN JAVA java.net PACKAGE

  2. Programming with Sockets Developing a TCP Client Developing a TCP Server Client/Server Applications using UDP Writing a Multithreaded Server Network Application Programming Techniques Multi-Protocol Programming using URLs Passing Java Objects JSSE - Java Secure Socket Extension JavaRMI JavaRMI Architecture Programming with RMI

  3. Java Sockets • What is Socket? • A socket is a communication endpoint • an object through which an application sends or receives packets of data across a network. • The purpose is to abstract away the underlining network • Internet protocol (IP) is a low-level routing protocol that breaks data into small packets and send them to an address across a network • It doesnot guarantee to deliver said packages in to the destination • Transmission Control Protocol (TCP) is a higher- level protocol that manages to robustly string together these packets, sorting and retransmitting them as necessary to reliably transmit the data. • UserDatagram Protocol (UDP) is a third protocol can be used directly to support fast, connectionless, unreliable transport of packets

  4. A server runs on a specific computer and has a socket that is bound to a specific port number. • A client makes a connection request based on the host name of the server and the port number.

  5. Inacceptance case, the server gets a new socket bound to a different port. • If the connection is accepted, a socket is successfully created and the client can use the socket to communicate with the server.

  6. JAVA Socket Programming • Client side • Socket • This class implements client sockets • A socket is an endpoint for communication between two machines • Server side • ServerSocket • This class implements server sockets. • A server socket waits for requests to come in over the network. • It performs some operation based on that request, and then possibly returns a result to the requester.

  7. Server Create a server socket Start listening on a port Create a new socket Accept connection Sending & Receiving Client Create the socket Seek a connection Sending & Receiving Sequence of Operations for a TCP Socket Communication

  8. Opening a Socketwhile programming a client Socket MyClient;MyClient = new Socket("Machine name", PortNumber); Machine nameis the machine we are trying to open a connection to PortNumberis the port (a number) on which the server we are trying to connect to is running. • When selecting a port number, we should note that port numbers between 0 and 1023 are reserved for privileged users (that is, super user or root). • These port numbers are reserved for standard services, such as email, FTP, and HTTP. • When selecting a port number for our server, we select one that is greater than 1023

  9. Reserved Sockets • Once connected , a higher level protocol proceeds, which is dependent on which we are using • TCP/IP reserves the lower 1024 ports for specific protocols. Port Number 21 is for FTP 23 is for Telnet 25 is for e-mail 79 is for finger 80 is for HTTP, 119 is for netnews.

  10. PORT NUMBERS (last updated 2003-12-22) • The port numbers are divided into three ranges: • Well Known Portsare those from 0 through 1023 • Registered Ports are those from 1024 through 49151 • Dynamic and/or Private Ports are those from 49152 through 65535 http://www.iana.org/assignments/port-numbers Unassigned port numbers should not be used. The IANA will assign the number for the port after your application has been approved

  11. The code that opens a socketwhileprogramming a client can be written as follows by make use of exception handling: Socket MyClient;try {MyClient = new Socket("Machine name", PortNumber);}catch (IOException e) {    System.out.println(e);}

  12. Opening a socket while programming a server ServerSocket MyService;try {MyService = new ServerSocket(PortNumber);        }        catch (IOException e) {           System.out.println(e);        } • When implementing a server we also need to create a socket object from the ServerSocketin order to listen for and acceptconnections from clients. Socket clientSocket = null;try {serviceSocket = MyService.accept();        }catch (IOException e) {   System.out.println(e);}

  13. Example A client requests a single file, /index.html, and the server relies that it has successfully found the file and is sending it to the client

  14. Server Client Listens to port 80 Connects to port 80. Accepts the connection Writes “GET/index.html HTTP/1.0\n\n”. Reads up until the second end-of-line(\n). Sees that Get is a known command and that HTTP/1.0 is a valid protocol version Reads alocal file called /index.html Writes “HTTP/1.0 200 OK \ n \ n”. “200” means “here comes the file” Copies the contents of the file Reads the contents of the file and displays it. into the socket Hangs up Hangs up

  15. How do we create an input stream? • On the client side, we can use the DataInputStream class to create an input stream to receive response from the server: DataInputStream input;try {   input = new DataInputStream(MyClient.getInputStream());}catch (IOException e) {   System.out.println(e);} • The class DataInputStream allows us to read lines of text and Java primitive data types in a portable way. • It has methods such as read,readChar, readInt, readDouble, and readLine,. • We can use any function which suits our needs depending on the type of data that we receive from the server.

  16. How do we create an input stream? On the server side, we can use DataInputStream to receive input from the client: DataInputStreaminput;try {input = new DataInputStream(serviceSocket.getInputStream());}catch (IOException e) {   System.out.println(e);}

  17. How do we create an output stream? On the client side, we can create an output stream to send information to the server socket using the class PrintStream or DataOutputStream of java.io: PrintStreamoutput;try {output = new PrintStream(MyClient.getOutputStream());//Returns the OutputStream associated with the invoking socket }catch (IOException e) {   System.out.println(e);} The class DataOutputStream allows us to write Java primitive data types; many of its methods write a single Java primitive type to the output stream. The method writeBytes is a useful one.

  18. How do we create an output stream? On the server side, we can use the class PrintStream to send information to the client. PrintStream output;try {   output = new PrintStream(serviceSocket.getOutputStream());}catch (IOException e) {   System.out.println(e);}

  19. How do we close sockets? We should always close the output and input stream before you close the socket. • On the client side: try {           output.close();           input.close();MyClient.close();} catch (IOException e) {   System.out.println(e);} • On the server side: try { output.close();input.close();serviceSocket.close();MyService.close();} catch (IOException e) {   System.out.println(e);}

  20. Client Side – Socket(summary) Common methods A socket can be examined at any time for the address and port information associated with it, by use of the following methods: • getInetAddress() - Returns the address to which the socket is connected • getInputStream() - Returns an input stream for this socket • getOutputStream() - Returns an output stream for this socket. • getPort() - Returns the remote port to which this socket is connected • getLocalPort() returns the local port to whichthis Socket object is connected. • close() – close this socket

  21. Client Connection • PrintWriter • Print formatted representations of objects to a text-output stream. • It does not contain methods for writing raw bytes, for which a program should use Unicode byte streams. • BufferReader • Read text from a character-input stream, buffering characters so as to provide for the efficient reading of characters, arrays, and lines

  22. Client Side – Operation Open a socket • Client flows • Open a socket. • Open an input stream and output stream to the socket. • Read from and write to the stream according to the server's protocol. • Close the streams. • Close the socket. Open input/output stream Send/receive data close streams close socket

  23. Client Side import java.io.*; import java.net.*; public class EchoClient { public static void main(String[] args) throws IOException { Socket echoSocket = null; PrintWriterout = null; BufferedReader in = null; try { echoSocket = new Socket(“myComputer", 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: myComputer."); System.exit(1); }

  24. catch (IOException e) { System.err.println("Couldn't get I/O for " + "the connection to: myComputer."); System.exit(1); } BufferedReader stdIn = new BufferedReader( new InputStreamReader(System.in)); String userInput; while ((userInput = stdIn.readLine()) != null) { out.println(userInput); System.out.println("echo: " + in.readLine()); } out.close(); in.close(); stdIn.close(); echoSocket.close(); } }

  25. Server Side • Server flows • create a ServerSocket No need to bind and listen, the constructor has already done that. • accept a client call • Send/Receive data • close socket

  26. Server Side – Example import java.net.*; class SimpleTCPServer { public static void main(String a[]) throws Exception; { ServerSocket acceptor = new ServerSocket(1111); System.out.println("On port " + acceptor.getLocalPort()); while (true) { Socket client = acceptor.accpet(); // Do stuff here... client.close(); } } }

  27. import java.io.*;import java.net.*;public class smtpClient{// smtpClient: client socket    public static void main(String[] args) {     Socket smtpSocket = null;      DataOutputStream os = null;//os: output stream    DataInputStream is = null;// is: input stream // Initialization section:// Try to open a socket on port 25// Try to open input and output streams

  28. try {smtpSocket = new Socket("hostname", 25) os = newDataOutputStream(smtpSocket.getOutputStream());is = new DataInputStream(smtpSocket.getInputStream());     }catch (UnknownHostException e) { System.err.println("Don't know about host: hostname");  } catch (IOException e) {            System.err.println("Couldn't get I/O for the connection to: hostname");}

  29. // If everything has been initialized then we want to write some data // to the socket we have opened a connection to on port 25if (smtpSocket != null && os != null && is != null) {   try {// The capital string before each colon has a special meaning to SMTP// you may want to read the SMTP specification, RFC1822/3os.writeBytes("HELO\n"); os.writeBytes("MAIL From: z.altan@iku.edu.tr\n");os.writeBytes("RCPT To: z.altan@iku.edu.tr\n");os.writeBytes("DATA\n");os.writeBytes("From: z.altan@iku.edu.tr\n");os.writeBytes("Subject: testing\n");os.writeBytes(“Okey \n"); // message bodyos.writeBytes("\n.\n");os.writeBytes("QUIT");

  30. // keep on reading from/to the socket till we receive the "Ok" from SMTP, // once we received that then we want to break.String responseLine;          while ((responseLine = is.readLine()) != null) {         System.out.println("Server: " + responseLine);                    if (responseLine.indexOf("Ok") != -1) {                      break;                    }                } os.close(); is.close();smtpSocket.close();        }catch (UnknownHostException e) {                System.err.println("Trying to connect to unknown host: " + e); } catch (IOException e) {                System.err.println("IOException:  " + e);   }    }    }           }

  31. Echo server • Now let's write a server. This • server is very similar to the echo server running on port7. • Basically, the echo server receives text from the client and then sends that exact text back to the client. • This is just about the simplest server we can write. • Note that this server handles only one client. • We can modify it to handle multiple clients using threads.

  32. import java.io.*;import java.net.*;public class echo3 {    public static void main(String args[]) {// declaration section:// declare a server socket and a client socket for the server// declare an input and an output stream        ServerSocket echoServer = null;        String line;        DataInputStream is;        PrintStream os;        Socket clientSocket = null;// Try to open a server socket on port 9999// Note that we can't choose a port less than 1023 if we are not// privileged users (root)        try {echoServer = new ServerSocket(9999);        }        catch (IOException e) {           System.out.println(e);        }  

  33. // Create a socket object from the ServerSocket to listen and accept // connections. //Open input and output streamstry {clientSocket = echoServer.accept();is = new DataInputStream(clientSocket.getInputStream());os = new PrintStream(clientSocket.getOutputStream());// As long as we receive data, echo that data back to the client.           while (true) {             line = is.readLine();os.println(line);            }        }   catch (IOException e) {           System.out.println(e);        }    }}

  34. URLConnection

  35. Creating a URL try { // With components. URL url = new URL("http", "hostname", 80, "index.html"); // With a single string. url = new, URL("http://hostname:80/index.html"); } , catch (MalformedURLException e) { }

  36. Getting Text from a URL try { // Create a URL for the desired page URL url = new URL("http://hostname:80/index.html"); // Read all the text returned by the server BufferedReaderin = new BufferedReader(new InputStreamReader (url.openStream())); String str; while ((str = in.readLine()) != null) { // str is one line of text; // readLine() strips the newline character(s) } in.close(); } catch (MalformedURLException e) { } catch (IOException e) { }

  37. Getting an Image from a URL try { // Create a URL for the image's location URL url = new URL("http://hostname:80/image.gif"); // Get the image java.awt.Imageimage = java.awt.Toolkit.getDefaultToolkit().createImage(url); } catch (MalformedURLException e) { } catch (IOException e) { }

  38. Reference Web Links Socket programming http://java.sun.com/docs/books/tutorial/networking/ SMTP protocol: http://www.ietf.org/rfc/rfc821.txt

  39. Java Remote Method Invocation (Java RMI) • Java RMI enables the programmer to create distributed Java technology-based to Java technology-based applications • the methods of remote Java objects can be invoked from other Java virtual machines, possibly on different hosts. • RMI uses object serialization to marshal and unmarshal parameters and does not truncate types, supporting true object-oriented polymorphism http://abra.sourceforge.net/doc/javadoc/org/ephman/abra/tools/Marshaller.html

More Related