Quick walk through the advanced concepts in Java - Part 3 of series
Chapters
Getting started with Networking
Networking in java is a concept of connecting computing devices to each other so that user can share resources.
The java.net package of the java contains a group of interfaces and classes that provide the low-level communication details.
The two common network protocols:
- TCP: TCP(Transmission Control Protocol) allows reliable communication between two applications. TCP is typically used over Internet Protocol which is known to as TCP/IP.
- UDP: UDP(User Datagram Protocol) a connection-less protocol allows for packets of data to be transmitted between applications.
image source: Oracle.com
We will explore the following two topics in this tutorial
- Socket Programming: provides an option to share data between different computing devices.
- Working with URLs: URL stands for Uniform Resource Locator
Socket programming
A socket is one end-point of a two-way communication link between two programs running on the network on different machines. A network can either be LAN or WAN etc. The java.net package provides two classes
- Socket and
- ServerSocket
These 2 classes implement the client side of the connection on one machine and the server side of the connection on server machine, respectively.
Socket programming is used to establish a communication between the devices running on different JRE. Socket programming can be connection-less or connection-oriented.
The client in socket programming required:
- Port number
- Server IP Address
Socket class:
A socket is an endpoint between the machines for communication. These Socket classes mainly used for socket creation, The Socket class methods are:
- public InputStream getInputStream():to get the InputStream attached with socket.
- public OutputStream getOutputStream():to get the OutputStream attached with socket.
- public synchronized void close():to close the socket
ServerSocket class:
This class can be used for a server socket creation. To establish communication with the clients by usingthis object
The ServerSocket class methods are:
- public Socket accept(): which returns the establish connection between server and client and also socket.
- public synchronized void close(): to close the server socket
- publicintgetLocalPort()
Returns the port that the server socket is listening on.
Example:
Java Socket Programming
ServerExample.java
import java.io.DataInputStream; import java.net.ServerSocket; import java.net.Socket; public class ServerExample { public static void main(String[] args) { try { ServerSocket soc = newServerSocket(6666); Socket sa = soc.accept(); //To establishes connection DataInputStream dis = newDataInputStream(sa.getInputStream()); String msg = (String) dis.readUTF(); System.out.println("The message= " + msg); soc.close(); } catch (Exception e) { System.out.println(e); } } }
ClientExample.java
import java.io.DataOutputStream; import java.net.Socket; public class ClientExample { public static void main(String[] args) { try { Socket soc = new Socket("localhost", 6666); DataOutputStream dos = new DataOutputStream(soc.getOutputStream()); dos.writeUTF("Server..."); dos.flush(); dos.close(); soc.close(); } catch (Exception e) { System.out.println(e); } } }
Open two command prompts to execute this program. Compile the program using “javac” command, and run the program by using “java” command as shown below. After executing the client application, on the server console a message will be displayed.
Working with URLs
URL stands for Uniform Resource Locator. It basically represents a resource on Internet. You use browsers such as Firefox or Chrome to browser URLs. URLs can be of various form, such as ftp, http, git, etc
An URL contains the following parts
Host Name: This is the name of the server, you are trying to connect to, to locate a resource
Filename: This is a resource itself, file can be of various extensions such as a.html, a.php, a.pl, a,py, a.asp etc
Port Number: The port number to which to connect. Generally port 80, or 143 but is entirely optional. In case you are using a non standard port such as 8080 then you would have to provide a port number to connect to the server.
Reference: A reference to a named anchor (if any).
URL Class Methods:
The java.net.URL class represents a URL. This class provide an API to work with URLs.
The URL class has several constructors for creating URLs, including the following:
Constructor Summary
Constructor and Description |
---|
URL(String spec)
This constructor creates a URL from a string
|
URL(String protocol, String host, int port, String file)
This constructor creates a URL from protocol, host, port and resource file values.
|
URL(String protocol, String host, int port, String file, URLStreamHandler handler)
Identical to above constructor but you are able to pass a URL stream
handler (if any) . |
URL(String protocol, String host, String file)
Creates a URL from
protocol name, host name, and file name. |
URL(URL context, String spec)
Creates a URL from
|
URL(URL context, String spec, URLStreamHandler handler)
Creates a URL by parsing the given spec with the specified handler within a specified context.
|
Info source: Oracle.com
Method Summary
Modifier and Type | Method and Description |
---|---|
boolean |
equals(Object obj)
Compares this URL for equality with another object.
|
String |
getAuthority()
Gets the authority part of this
URL . |
Object |
getContent()
Gets the contents of this URL.
|
Object |
getContent(Class[] classes)
Gets the contents of this URL.
|
int |
getDefaultPort()
Gets the default port number of the protocol associated with this
URL . |
String |
getFile()
Gets the file name of this
URL . |
String |
getHost()
Gets the host name of this
URL , if applicable. |
String |
getPath()
Gets the path part of this
URL . |
int |
getPort()
Gets the port number of this
URL . |
String |
getProtocol()
Gets the protocol name of this
URL . |
String |
getQuery()
Gets the query part of this
URL . |
String |
getRef()
Gets the anchor (also known as the "reference") of this
URL . |
String |
getUserInfo()
Gets the userInfo part of this
URL . |
int |
hashCode()
Creates an integer suitable for hash table indexing.
|
URLConnection |
openConnection()
Returns a
URLConnection instance that represents a connection to the remote object referred to by the URL . |
URLConnection |
openConnection(Proxy proxy)
Same as
openConnection() , except that the connection will be made through the specified proxy; Protocol handlers that do not support proxing will ignore the proxy parameter and make a normal connection. |
InputStream |
openStream()
Opens a connection to this
URL and returns an InputStream for reading from that connection. |
boolean |
sameFile(URL other)
Compares two URLs, excluding the fragment component.
|
protected void |
set(String protocol, String host, int port, String file, String ref)
Sets the fields of the URL.
|
protected void |
set(String protocol, String host, int port, String authority, String userInfo, String path, String query, String ref)
Sets the specified 8 fields of the URL.
|
static void |
setURLStreamHandlerFactory(URLStreamHandlerFactory fac)
Sets an application's
URLStreamHandlerFactory . |
String |
toExternalForm()
Constructs a string representation of this
URL . |
String |
toString()
Constructs a string representation of this
URL . |
URI |
toURI()
Returns a
URI equivalent to this URL. |
How to create a URL
We will use a URL class as shown below
URL myURL = new URL("https://www.subjectcoach.com/");
Example utilizing various methods of URL class
import java.net.*; import java.io.*; public class URLExample { public static void main(String [] args) { try { URL url = new URL("https://www.subjectcoach.com#testref"); System.out.println("URL value " + url.toString()); System.out.println("Protocol value " + url.getProtocol());
System.out.println("Default Port: "+url.getDefaultPort()); System.out.println("Authority is " + url.getAuthority()); System.out.println("Resource Name: " + url.getFile()); System.out.println("Host: " + url.getHost()); System.out.println("Port: " + url.getPort()); System.out.println("Query String: " + url.getQuery()); System.out.println("Ref: " + url.getRef()); }catch(IOException e) { e.printStackTrace(); } } }
Output
URL value https://www.subjectcoach.com#testref
Protocol value https
Default Port: 443
Authority is www.subjectcoach.com
Resource Name:
Host: www.subjectcoach.com
Port: -1
Query String: null
Ref: testref
URLConnections Class:
The class URLConnection
is an abstract class which is superclass of all classes that represent a communications link between the application and a URL. If you want to read from or write to the resource, which is referenced by URL classs, you will use this class methods.
source: oracle.com
Core methods |
---|
Object getContent() Return the contents read from a resource |
Object getContent(Class[] classes) Retrieves the contents of this URL connection. |
String getContentEncoding() Returns the value of the content-encoding header field. |
int getContentLength() Returns the value of the content-length header field. |
String getContentType() Returns the value of the content-type header field. |
int getLastModified() Returns the value of the last-modified header field. |
long getExpiration() Returns the value of the expires header field. |
long getIfModifiedSince() Returns the value of this object's ifModifiedSince field. |
public void setDoInput(boolean input) Passes in true to denote that the connection will be used for input. The default value is true because clients typically read from a URLConnection. |
public void setDoOutput(boolean output) Passes in true to denote that the connection will be used for output. The default value is false because many types of URLs do not support being written to. |
public InputStream getInputStream() throws IOException Returns the input stream of the URL connection for reading from the resource. |
public OutputStream getOutputStream() throws IOException Returns the output stream of the URL connection for writing to the resource |
public URL getURL() Returns the URL that this URLConnection object is connected to |
Example:
The example below highlights the use of URLConnection class.import java.net.*; import java.io.*; public class file { public static void main(String [] args) { try { URL url = new URL("http://www.google.com"); URLConnection urlConnection = url.openConnection(); HttpURLConnection connection = null; if(urlConnection instanceof HttpURLConnection) { connection = (HttpURLConnection) urlConnection; } else { throw new Exception("Invalid URL"); } BufferedReader in = new BufferedReader( new InputStreamReader(connection.getInputStream())); String pageContents = ""; String line; while((line = in.readLine()) != null) { pageContents += line; } System.out.println(pageContents); }catch(Exception e) { e.printStackTrace(); } } }
Output
Description
This is the last part in our tutorial series on Java. This tutorial is designed as a quick walk through the advanced concepts of Java Languages. This tutorial is subdivided into few chapters as shown below
- Data Structures
- Collections
- Generics
- Serialization
- Networking
- Working with Emails
- Multithreading
- Getting started with Applets
- JavaDoc
Let us know if you find any issues with this tutorial. Also, if you can provide us with your feedback, that always help us improve.
Prerequisites
You must have read Part 1 and Part 2 of our tutorial series on Java.
Audience
Beginners or students looking to brush up their Java knowledge
Learning Objectives
To get an understanding on some of the advanced topics of Java.
Author: Subject Coach
Added on: 10th Mar 2015
You must be logged in as Student to ask a Question.
None just yet!