Core Java -NetworkingThe term network programming refers to writing programs that execute across multiple devices (computers), in which the devices are all connected to each other using a network. The java.net package of the J2SE APIs contains a collection of classes and interfaces that provide the low-level communication details, allowing you to write programs that focus on solving the problem at hand. The java.net package provides support for the two common network protocols: This tutorial gives good understanding on the following two subjects: Url Processing : URL stands for Uniform Resource Locator and represents a resource on the World Wide Web, such as a Web page or FTP directory. This section shows you how to write Java programs that communicate with a URL. A URL can be broken down into parts, as follows: protocol://host:port/path?query#refExamples of protocols include HTTP, HTTPS, FTP, and File. The path is also referred to as the filename, and the host is also called the authority. The following is a URL to a Web page whose protocol is HTTP: https://www.google.com/Notice that this URL does not specify a port, in which case the default port for the protocol is used. With HTTP, the default port is 80. URL Class Methods : The java.net.URL class represents a URL and has complete set of methods to manipulate URL in Java. The URL class has several constructors for creating URLs, including the following: S.No Methods Description ---- ----------------------------------------------------------- ----------------------------------------------------- 1 public URL(String protocol, String host, int port, String Creates a URL by putting together the given parts. file) throws MalformedURLException. 2 public URL(String protocol, String host, String file) Identical to the previous constructor, except throws MalformedURLException that the default port for the given protocol is used. 3 public URL(String url) throws Creates a URL from the given String. MalformedURLException 4 public URL(URL context, String url) throws Creates a URL by parsing the together the MalformedURLException URL and String argumentsThe URL class contains many methods for accessing the various parts of the URL being represented. Some of the methods in the URL class include the following: S.No Methods Description ---- ------------------------------------- ----------------------------------------------------- 1 public String getPath() Returns the path of the URL. 2 public String getQuery() Returns the query part of the URL. 3 public String getAuthority() Returns the authority of the URL. 4 public int getPort() Returns the port of the URL. 5 public int getDefaultPort() Returns the default port for the protocol of the URL. 6 public String getProtocol() Returns the protocol of the URL. 7 public String getHost() Returns the host of the URL. 8 public String getFile() Returns the filename of the URL. 9 public String getRef() Returns the reference part of the URL. 10 public URLConnection openConnection() Opens a connection to the URL, allowing a client to throws IOException communicate with the resource.Eg: The following URLDemo program demonstrates the various parts of a URL. A URL is entered on the command line, and the URLDemo program outputs each part of the given URL. import java.net.*; import java.io.*; public class URLDemo{ public static void main(String[] args){ try{ URL url =new URL("https://www.google.com/"); System.out.println("URL is : "+ url.toString()); System.out.println("protocol is : "+ url.getProtocol()); System.out.println("authority is : "+ url.getAuthority()); System.out.println("file name is : "+ url.getFile()); System.out.println("host is : "+ url.getHost()); System.out.println("path is : "+ url.getPath()); System.out.println("port is : "+ url.getPort()); System.out.println("default port is : "+ url.getDefaultPort()); System.out.println("query is : "+ url.getQuery()); System.out.println("ref is : "+ url.getRef()); }catch(IOException e){ e.printStackTrace(); } } }Output : URL is : https://www.google.com/ protocol is : https authority is : www.google.com file name is : / host is : www.google.com path is : / port is : -1 default port is : 443 query is : null ref is : null URLConnections Class Methods : The openConnection() method returns a java.net.URLConnection, an abstract class whose subclasses represent the various types of URL connections. For eg: The URLConnection class has many methods for setting or determining information about the connection, including the following: S.No Methods Description ---- ------------------------------------- ---------------------------------------------------------------- 1 Object getContent() Retrieves the contents of this URL connection. 2 int getContentLength() Returns the value of the content-length header field. 3 String getContentType() Returns the value of the content-type header field. 4 int getLastModified() Returns the value of the last-modified header field. 5 public URL getURL() Returns the URL that this URLConnection object is connected to. 6 public InputStream getInputStream() throws Returns the input stream of the URL connection for reading from IOException the resource. 7 public OutputStream getOutputStream() throws Returns the output stream of the URL connection for writing to IOException the resource.Eg: The following URLConnectionDemo program connects to a URL entered from the command line. If the URL represents an HTTP resource, the connection is cast to HttpURLConnection, and the data in the resource is read one line at a time. Eg: import java.net.*; //File Name : URLConnDemo.java import java.io.*; public class URLConnDemo{ public static void main(String[] args){ try{ URL url =new URL("https://www.google.com/"); URLConnection urlConnection = url.openConnection(); HttpURLConnection connection =null; if(urlConnection instanceof HttpURLConnection){ connection =(HttpURLConnection) urlConnection; }else{ System.out.println("Please enter an HTTP URL."); return; } BufferedReader in=new BufferedReader( new InputStreamReader(connection.getInputStream())); String urlString =""; String current; while((current =in.readLine())!=null){ urlString += current; } System.out.print(urlString); }catch(IOException e){ e.printStackTrace(); } } }Output : $ java URLConnDemo https://www.google.com/ .....a complete HTML content of home page of google.com..... Socket Programming : Sockets provide the communication mechanism between two computers using TCP. A client program creates a socket on its end of the communication and attempts to connect that socket to a server. When the connection is made, the server creates a socket object on its end of the communication. The client and server can now communicate by writing to and reading from the socket. The java.net.Socket class represents a socket, and the java.net.ServerSocket class provides a mechanism for the server program to listen for clients and establish connections with them. The following steps occur when establishing a TCP connection between two computers using sockets: After the connections are established, communication can occur using I/O streams. Each socket has both an OutputStream and an InputStream. The client's OutputStream is connected to the server's InputStream, and the client's InputStream is connected to the server's OutputStream. TCP is a twoway communication protocol, so data can be sent across both streams at the same time. There are following usefull classes providing complete set of methods to implement sockets. ServerSocket Class Methods : The java.net.ServerSocket class is used by server applications to obtain a port and listen for client requests The ServerSocket class has four constructors: S.No Methods Description ---- ------------------------------------- -------------------------------------------------------------------------- 1 public ServerSocket(int port) Attempts to create a server socket bound to the specified port. An throws IOException exception occurs if the port is already bound by another application. 2 public ServerSocket(int port, int Similar to the previous constructor, the backlog parameter specifies backlog) throws IOException how many incoming clients to store in a wait queue. 3 public ServerSocket(int port, int Similar to the previous constructor, the InetAddress parameter specifies the backlog, InetAddress address) local IP address to bind to. The InetAddress is used for servers that may throws IOException have multiple IP addresses, allowing the server to specify which of its IP addresses to accept client requests on. 4 public ServerSocket() throws IOException Creates an unbound server socket. When using this constructor, use the bind() method when you are ready to bind the server socketIf the ServerSocket constructor does not throw an exception, it means that your application has successfully bound to the specified port and is ready for client requests. Here are some of the common methods of the ServerSocket class: S.No Methods Description ---- ----------------------------- ----------------------------------------------------------------------------------------- 1 public int getLocalPort() Returns the port that the server socket is listening on. This method is useful if you passed in 0 as the port number in a constructor and let the server find a port for you. 2 public Socket accept() Waits for an incoming client. This method blocks until either a client connects to throws IOException the server on the specified port or the socket times out, assuming that the time-out value has been set using the setSoTimeout() method. Otherwise, this method blocks indefinitely. 3 public void setSoTimeout(int Sets the time-out value for how long the server socket waits for a client during the timeout) accept(). 4 public void Binds the socket to the specified server and port in the SocketAddress object. Use bind(SocketAddress host, this method if you instantiated the ServerSocket using the no-argument constructor. int backlog)When the ServerSocket invokes accept(), the method does not return until a client connects. After a client does connect, the ServerSocket creates a new Socket on an unspecified port and returns a reference to this new Socket. A TCP connection now exists between the client and server, and communication can begin. Socket Class Methods : The java.net.Socket class represents the socket that both the client and server use to communicate with each other. The client obtains a Socket object by instantiating one, whereas the server obtains a Socket object from the return value of the accept() method. The Socket class has five constructors that a client uses to connect to a server: S.No Methods Description ---- ------------------------------------------------ ------------------------------------------------------------------------ 1 public Socket(String host, int port) throws This method attempts to connect to the specified server at the UnknownHostException, IOException specified port. If this constructor does not throw an exception, the connection is successful and the client is connected to the server. 2 public Socket(InetAddress host, int port) throws This method is identical to the previous constructor, except that the IOException host is denoted by an InetAddress object. 3 public Socket(String host, int port, InetAddress Connects to the specified host and port, creating a socket on the localAddress, int localPort) throws IOException local host at the specified address and port. 4 public Socket(InetAddress host, int port, This method is identical to the previous constructor, except that the InetAddress localAddress, int localPort) throws host is denoted by an InetAddress object instead of a String. IOException 5 public Socket() Creates an unconnected socket. Use the connect() method to connect this socket to a server.When the Socket constructor returns, it does not simply instantiate a Socket object but it actually attempts to connect to the specified server and port. Some methods of interest in the Socket class are listed here. Notice that both the client and server have a Socket object, so these methods can be invoked by both the client and server. S.No Methods Description ---- -------------------------------------------- ------------------------------------------------------------------------ 1 public void connect(SocketAddress host, int This method connects the socket to the specified host. This method is timeout) throws IOException needed only when you instantiated the Socket using the no-argument constructor. 2 public InetAddress getInetAddress() This method returns the address of the other computer that this socket is connected to. 3 public int getPort() Returns the port the socket is bound to on the remote machine. 4 public int getLocalPort() Returns the port the socket is bound to on the local machine. 5 public SocketAddress getRemoteSocketAddress() Returns the address of the remote socket. 6 public InputStream getInputStream() throws Returns the input stream of the socket. The input stream is connected IOException to the output stream of the remote socket. 7 public OutputStream getOutputStream() throws Returns the output stream of the socket. The output stream is IOException connected to the input stream of the remote socket. 8 public void close() throws IOException Closes the socket, which makes this Socket object no longer capable of connecting again to any serverInetAddress Class Methods : This class represents an Internet Protocol (IP) address. Here are following useful methods, which you would need while doing socket programming: S.No Methods Description ---- -------------------------------------------- ------------------------------------------------------------------------ 1 static InetAddress getByAddress(byte[] addr) Returns an InetAddress object given the raw IP address. 2 static InetAddress getByAddress(String host, Create an InetAddress based on the provided host name and IP address. byte[] addr) 3 static InetAddress getByName(String host) Determines the IP address of a host, given the host's name. 4 String getHostAddress() Returns the IP address string in textual presentation. 5 String getHostName() Gets the host name for this IP address. 6 static InetAddress InetAddress getLocalHost() Returns the local host. 7 String toString() Converts this IP address to a String.Socket Client Example : The following ClientSide is a client program that connects to a server by using a socket and sends a greeting, and then waits for a response. import java.io.*; import java.net.*; public class ClientSide { public static void main(String[] args) { try{ Socket s=new Socket("localhost",8888); DataOutputStream dout=new DataOutputStream(s.getOutputStream()); dout.writeUTF("Hello Server1"); dout.flush(); dout.close(); s.close(); }catch(Exception e){ System.out.println(e); System.out.println("Exception-Client side"); } } }Socket Server Example : The following GreetingServer program is an example of a server application that uses the Socket class to listen for clients on a port number specified by a command-line argument: import java.io.*; import java.net.*; public class ServerSide { public static void main(String[] args){ try{ ServerSocket ss=new ServerSocket(8888); Socket s=ss.accept(); //establishes connection DataInputStream dis=new DataInputStream(s.getInputStream()); String str=(String)dis.readUTF(); System.out.println("message= "+str); ss.close(); }catch(Exception e){ System.out.println(e); System.out.println("Exception-Server side"); } } }Compile client and server and then start server as follows: Compile >javac ClientSide.java >javac ServerSide.java Run >java ServerSide >java ClientSide Output : message= Hello Server1 The above given message in ClientSide will be displayed in ServerSide by the operation of compiling and running the ClientSide and ServerSide. ☛ Join to Learn from Experts: Java / J2EE Developer Training in Chennai by TesDBAcademy
« Previous
Next Topic »
(Core Java - Regex)
|