Networking Java Socket Programming

26
JAVA NETWORKING

Transcript of Networking Java Socket Programming

Page 1: Networking Java Socket Programming

JAVA NETWORKING

Page 2: Networking Java Socket Programming

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.

Page 3: Networking Java Socket Programming

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”.

Page 4: Networking Java Socket Programming

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

Page 5: Networking Java Socket Programming

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 128.250.25.158 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 www.google.com, which are easier to remember.

Domain name servers(DNS) translate these names to IP addresses.

Page 6: Networking Java Socket Programming

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.

Page 7: Networking Java Socket Programming

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.

Page 8: Networking Java Socket Programming
Page 9: Networking Java Socket Programming

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 java.net, to enable the rapid development of network applications.

The two key classes from the java.net package used in creation of server and client programs are: ServerSocket Socket

Page 10: Networking Java Socket Programming

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.

Page 11: Networking Java Socket Programming

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 clientDataInputStream is = new DataInputStream(client.getInputStream());DataOutputStream os = new DataOutputStream(client.getOutputStream());

4. Perform communication with clientReceive from client: String line = is.readLine();Send to client: os.writeBytes(“Hello\n”);

5. Close socket:client.close();

Page 12: Networking Java Socket Programming

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(“Hello\n”);

4. Close the socket when done:client.close();

Page 13: Networking Java Socket Programming

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("mail.yourserver.com", 25); // 25 is

PrintWriter out = new PrintWriter(s.getOutputStream());

2. Send the following information to the print stream:HELO sending hostMAIL FROM: <sender email address>RCPT TO: <recipient email address>DATAmail message(any number of lines).QUIT

Page 14: Networking Java Socket Programming

Most SMTP servers do not check the veracity of the information—you may be able to supply any sender you like.

Page 15: Networking Java Socket Programming

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 132.163.4.102. 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(“india.gov");returns an InetAddress object that encapsulates the sequence of four bytes 132.163.4.102.

You can access the bytes with the getAddress method.byte[] addressBytes = address.getAddress();

Page 16: Networking Java Socket Programming

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 google.com 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 127.0.0.1, which isn't very useful. Instead, use the static getLocalHost method to get the address of your local host.

InetAddress address= InetAddress.getLocalHost();

Page 17: Networking Java Socket Programming

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;}

Page 18: Networking Java Socket Programming

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.

Page 19: Networking Java Socket Programming

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

Page 20: Networking Java Socket Programming

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.

Page 21: Networking Java Socket Programming

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

Page 22: Networking Java Socket Programming

To create servlets, you will need access to a servlet development environment.

The one we will use is Tomcat. Tomcat is an open-source 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.

Page 23: Networking Java Socket Programming

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.

Page 24: Networking Java Socket Programming

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.

Page 25: Networking Java Socket Programming

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.

Page 26: Networking Java Socket Programming

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.