Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

Networking Java Socket Programming


Published on

Published in: Technology, Education

Networking Java Socket Programming

  2. 2. CLIENT/SERVER COMMUNICATION At a basic level, network-based systems consist of a server , client , and a media for communication  A computer running a program that makes a request for services is called client machine.  A computer running a program that offers requested services from one or more clients is called server machine.  The media for communication can be wired or wireless network. 
  3. 3. Generally, programs running on client machines make requests to a program running on a server machine. They involve networking services provided by the transport layer, which is part of the Internet software stack, often called TCP/IP (Transport Control Protocol/Internet Protocol)  The transport layer comprises two types of protocols,   TCP (Transport Control Protocol)  UDP (User Datagram Protocol).  The most widely used programming interfaces for these protocols are “sockets”.
  4. 4. TCP is a connection-oriented protocol that provides a reliable flow of data between two computers. Example applications that use such services are HTTP, FTP, and Telnet.  UDP is a protocol that sends independent packets of data, called “datagrams”, from one computer to another with no guarantees about arrival and sequencing. Example applications that use such services include Clock server and Ping.  The TCP and UDP protocols use “ports” to map incoming data to a particular process running on a computer.  Port is represented by a positive (16-bit) integer value 
  5. 5. Some ports have been reserved to support common/well known services like ftp, http, https etc.  User-level process/services generally use port number value >= 1024.  Every computer on the Internet is identified by a unique, 4-byte IP address .  This is typically written in dotted quad format like where each byte is an unsigned value between 0 and 255.  This representation is not user-friendly because it does not tell us anything about the content and then it is difficult to remember. Hence, IP addresses are mapped to names like, which are easier to remember.  Domain name servers(DNS) translate these names to IP addresses. 
  6. 6. Computers often need to communicate and provide more than one type of service or to talk to multiple hosts/computers at a time. For example, there may be multiple ftp sessions, web connections, and chat programs all running at the same time.  To distinguish these services, a concept of “port” s, a logical access point, represented by a 16-bit integer number is used.  That means, each service offered by a computer is uniquely identified by a port number.  Each Internet packet contains both the destination host address and the port number on that host to which the message/request has to be delivered.  The host computer dispatches the packets it receives to programs by looking at the port numbers specified within the packets. 
  7. 7. SOCKET Sockets provide an interface for programming networks at the transport layer.  A server runs on a specific computer and has a socket that is bound to a specific port.  The server listens to the socket for a client to make a connection request  If everything goes well, the server accepts the connection.  Upon acceptance, the server gets a new socket bound to a different port. It needs a new socket (consequently a different port number) so that it can continue to listen to the original socket for connection requests while serving the connected client. 
  8. 8. Socket is bound to a port number so that the TCP layer can identify the application that data is destined to be sent.  Java provides a set of classes, defined in a package called, to enable the rapid development of network applications.  The two key classes from the package used in creation of server and client programs are:   ServerSocket  Socket
  9. 9. SOCKET PROGRAMMING USING TCP  A server program creates a specific type of socket that is used to listen for client requests (server socket), In the case of a connection request, the program creates a new socket through which it will exchange data with the client using input and output streams.
  10. 10. STEPS TO CREATE SERVER PROGRAM 1. Open the Server Socket: ServerSocket server = new ServerSocket( PORT ); 2. Wait for the Client Request: Socket client = server.accept(); 3. Create I/O streams for communicating to the client DataInputStream is = new DataInputStream(client.getInputStream()); DataOutputStream os = new DataOutputStream(client.getOutputStream()); 4. Perform communication with client Receive from client: String line = is.readLine(); Send to client: os.writeBytes(“Hellon”); 5. Close socket: client.close();
  11. 11. STEPS TO CREATE CLIENT PROGRAM 1. Create a Socket Object: Socket client = new Socket(server, port_id); 2. Create I/O streams for communicating with the server. is = new DataInputStream(client.getInputStream()); os = new DataOutputStream(client.getOutputStream()); 3. Perform I/O or communication with the server: Receive data from the server: String line = is.readLine(); Send data to the server: os.writeBytes(“Hellon”); 4. Close the socket when done: client.close();
  12. 12. Sending E-Mail To send e-mail, you make a socket connection to port 25, the SMTP port. SMTP is the Simple Mail Transport Protocol that describes the format for e-mail messages. 1. Open a socket to your host. Socket s = new Socket("", 25); // 25 is PrintWriter out = new PrintWriter(s.getOutputStream()); 2. Send the following information to the print stream:  HELO sending host MAIL FROM: <sender email address> RCPT TO: <recipient email address> DATA mail message (any number of lines) . QUIT
  13. 13.  Most SMTP servers do not check the veracity of the information—you may be able to supply any sender you like.
  14. 14. Internet addresses Usually, you don't have to worry too much about Internet addresses—the numerical host addresses that consist of four bytes such as However, you can use the InetAddress class if you need to convert between host names and Internet addresses.  The static getByName method returns an InetAddress object of a host.  For example, InetAddress address= InetAddress.getByName(“"); returns an InetAddress object that encapsulates the sequence of four bytes  You can access the bytes with the getAddress method. byte[] addressBytes = address.getAddress(); 
  15. 15. Some host names with a lot of traffic correspond to multiple Internet addresses, to facilitate load balancing.  For example, at the time of this writing, the host name corresponds to different Internet addresses. One of them is picked at random when the host is accessed. You can get all hosts with the getAllByName method. InetAddress[] addresses =InetAddress.getAllByName(host);  Finally, you sometimes need the address of the local host. If you simply ask for the address of localhost, you always get the address, which isn't very useful. Instead, use the static getLocalHost method to get the address of your local host. InetAddress address= InetAddress.getLocalHost(); 
  16. 16. URL Connections  The URL and URLConnection classes encapsulate much of the complexity of retrieving information from a remote site.    URL url = new URL(urlString); The Java 2 platform supports both HTTP and FTP resources. If you simply want to fetch the contents of the resource, then you can use the openStream method of the URL class. This method yields an InputStream object. Using this stream object, you can easily read the contents of the resource. InputStream uin = url.openStream(); BufferedReader in = new BufferedReader(new InputStreamReader(uin)); String line; while ((line = in.readLine()) != null) { process line; }
  17. 17. Posting Form Data we saw how to read data from a web server. Now we learn how your programs can send data back to a web server and to programs that the web server invokes, using the CGI (Common Gateway Interface).  check boxes and radio buttons are sent back to the server to be processed by a CGI script.  The CGI script to use is specified in the ACTION attribute of the FORM tag.  The CGI script is a program that resides on the server computer. The web server launches the CGI script and feeds it the form data. 
  18. 18. What Is a Servlet?      Servlets are small programs that execute on the server side of a web connection. Just as applets dynamically extend the functionality of a web browser, servlets dynamically extend the functionality of a web server. In the early days of the Web, a server could dynamically construct a page by creating a separate process to handle each client request. It communicated with the web server via an interface Common Gateway Interface (CGI). CGI allowed the separate process to read data from the HTTP request and write data to the HTTP response. CGI suffered serious performance problems.    It was expensive in terms of processor and memory resources to create a separate process for each client request. It was also expensive to open and close database connections for each client request The CGI programs were not platform-independent
  19. 19. Advantages of Servlets       Servlets offer several advantages in comparison with CGI. Performance is significantly better. Servlets execute within the address space of a web server. It is not necessary to create a separate process to handle each client request. servlets are platform-independent because they are written in Java. the Java security manager on the server enforces a set of restrictions to protect the resources on a server machine. Finally, the full functionality of the Java class libraries is available to a servlet. It can communicate with applets, databases, or other software via the sockets that you have seen already.
  20. 20. The Life Cycle of a Servlet       init( ), service( ), and destroy( ) methods HTTP request for generated for a URL. Web server maps this request to a particular servlet which is dynamically retrieved and loaded. The server invokes the init( ) method of the servlet. The server invokes the service( ) method of the servlet; may also formulate an HTTP response for the client. The server may decide to unload the servlet from its memory using destroy() method
  21. 21. To create servlets, you will need access to a servlet development environment.  The one we will use is Tomcat. Tomcat is an opensource product maintained by the Jakarta Project of the Apache Software Foundation. It contains the class libraries, documentation, and runtime support that you will need to create and test servlets. 
  22. 22. Servlet API  javax.servlet Package  Interfaces Description        Servlet- Declares life cycle methods for a servlet. ServletConfig- Allows servlets to get initialization parameters. ServletContext- Enables servlets to log events and access information about their environment. ServletRequest- Used to read data from a client request. ServletResponse- Used to write data to a client response. SingleThreadModel- Indicates that the servlet is thread safe.
  23. 23. Servlet API Contd…  Classes Description GenericServlet- Implements the Servlet and ServletConfig interfaces.  ServletInputStream- Provides an input stream for reading requests from a client.  ServletOutputStream- Provides an output stream for writing responses to a client.  ServletException- Indicates a servlet error occurred.  UnavailableException- Indicates a servlet is unavailable. 
  24. 24. Servlet API Contd…  javax.servlet.http Package  Interface Description HttpServletRequest Enables servlets to read data from an HTTP request.  HttpServletResponse Enables servlets to write data to an HTTP response.  HttpSession Allows session data to be read and written. 
  25. 25. Servlet API Contd…  Classes Description Cookie- Allows state information to be stored on a client machine.  HttpServlet- Provides methods to handle HTTP requests and  responses.  HttpSessionEvent- Encapsulates a session-changed event. 