TCP/IP Network in Java


Topics interesting only for Java programmers

Link to this posting

Postby Ursego » 05 Mar 2019, 07:48

To see the keywords colored, save the following text in a text file and open it in a Java compiler (or in Notepad++ and select in the menu: Language > J > Java).

Code: Select all
// ******* The URL Class:

// The URL class is the gateway to any of the resource available on internet. A Class URL represents a Uniform Resource Locator, which is a pointer to a "resource" on the World Wide Web. A resource can point to a simple file or directory, or it can refer to a more complicated object, such as a query to a database or to a search engine. With the URL class, an application can open a connection to a server on the network and retrieve content with just a few lines of code. A URL is represented by an instance of the java.net.URL class.
import java.net.MalformedURLException;
import java.net.URL;
public class URLclass1 {
    public static void main(String[] args) throws MalformedURLException {
      try {
         // Create a URL with string representation:
         URL url1 = new URL("https://www.google.co.in/?gfe_rd=cr&ei=ptYqWK26I4fT8gfth6CACg#q=geeks+for+geeks+java");
    
         // Create a URL with a protocol, hostname and path:
         URL url2 = new URL("http", "www.geeksforgeeks.org",  "/jvm-works-jvm-architecture/");
    
         // Create a URL with a protocol, hostname, port and path and file:
         URL url3 = new URL("http", "baeldung.com", 9000, "/guidelines.txt");

         // Print the String representation of the URL:
         System.out.println(url1.toString()); // "https://www.google.co.in/?gfe_rd=cr&ei=ptYqWK26I4fT8gfth6CACg#q=geeks+for+geeks+java"
         System.out.println(url2.toString()); // "https://www.geeksforgeeks.org/jvm-works-jvm-architecture/"
         System.out.println(url3.toString()); // "http://baeldung.com:9000/guidelines.txt"

         // Parse URL address elements:
         URL url4 = new URL("https://www.google.co.in/search?q=gnu&rlz=1C1CHZL_enIN714IN715&oq=gnu&aqs=chrome..69i57j69i60l5.653j0j7&sourceid=chrome&ie=UTF-8#q=geeks+for+geeks+java");
          url4.getProtocol() // "https"
         url4.getHost()); // "www.google.co.in"
         url4.getDefaultPort() // "443"
         url4.getQuery() // retrieve the query part of URL (Query is the the part after the ‘?’ in the URL): "q=gnu&rlz=1C1CHZL_enIN714IN715&oq=gnu&aqs=chrome..69i57j69i60l5.653j0j7&sourceid=chrome&ie=UTF-8"
         url4.getPath() // "/search"
         url4.getFile() // retrive the file name: "/search?q=gnu&rlz=1C1CHZL_enIN714IN715&oq=gnu&aqs=chrome..69i57j69i60l5.653j0j7&sourceid=chrome&ie=UTF-8"
         url4.getRef() // retrieve the reference (usually, the reference is the part marked by a ‘#’ in the URL): "q=geeks+for+geeks+java"
      } catch ( MalformedURLException e ) { ... }
    }
}

// Stream Data:
// The lowest-level and most general way to get data back from a URL is to ask for an InputStream from the URL by calling openStream(). Getting the data as a stream may also be useful if you want to receive continuous updates from a dynamic information source. The drawback is that you have to parse the contents of the byte stream yourself. Working in this mode is basically the same as working with a byte stream from socket communications, but the URL protocol handler has already dealt with all of the server communications and is providing you with just the content portion of the transaction. The following code prints the contents of an HTML file on a web server:
try {
    URL url = new URL("http://server/index.html");
   // Ask for an InputStream with openStream() and wrap it in a BufferedReader to read the lines of text:
    BufferedReader bufferedReader = new BufferedReader (new InputStreamReader(url.openStream()));
    String line;
    while ((line = bufferedReader.readLine()) != null) System.out.println(line);
    bufferedReader.close();
} catch (Exception e) { }

// ******* The InetAddress Class:

// The java.net.InetAddress class is Java’s high-level representation of an IP address. It is used by most of the other networking classes, including Socket, ServerSocket, URL, and more. Usually, it includes both a hostname and an IP address.

// There are no public constructors in the InetAddress class. Instead, InetAddress has static factory methods that connect to a DNS server to resolve a hostname. The most common is InetAddress.getByName(). This method does not merely set a private String field in the InetAddress class. It actually makes a connection to the local DNS server to look up the name and the numeric address. If you've looked up this host previously, the information may be cached locally, in which case a network connection is not required. If the DNS server can't find the address, this method throws an UnknownHostException, a subclass of IOException.

// java.net.InetAddress methods:
public static InetAddress getByName(String host) throws UnknownHostException // returns the instance of InetAddress containing host name (like "www.javatpoint.com") and IP address (like "206.51.231.148")
public static InetAddress getLocalHost() throws UnknownHostException // returns the instance of InetAdddress containing LOCAL host name and IP aaddress
public String getHostName() // returns the host name of the IP address.
public String getHostAddress() // returns the IP address in string format.

import java.io.*; 
import java.net.*; 
public class InetDemo{ 
   public static void main(String[] args) { 
      try { 
         InetAddress ip = InetAddress.getByName("www.javatpoint.com");
         System.out.println(ip.getHostName()); // "www.javatpoint.com"
         System.out.println(ip.getHostAddress()); // "206.51.231.148"
         System.out.println(ip); // "www.javatpoint.com/206.51.231.148"
      } catch(UnknownHostException ex) {
         System.out.println("Could not find www.javatpoint.com");
      } 
   }
}

// The getLocalHost() method returns an InetAddress object for the host on which your code is running:
InetAddress me = InetAddress.getLocalHost();
// This method tries to connect to DNS to get a real hostname and IP address such as "elharo.laptop.corp.com" and "192.1.254.68"; but if that fails it may return the loopback address instead. This is the hostname "localhost" and the dotted quad address "127.0.0.1". Next example prints the address of the machine it's run on:
import java.net.*;
public class MyAddress {
   public static void main (String[] args) {
      try {
         InetAddress me = InetAddress.getLocalHost();
         System.out.println(me);
      } catch (UnknownHostException ex) {
         System.out.println("Could not find this computer's address.");
      }
   }
}

// If you know a numeric address, you can create an InetAddress object from that address without talking to DNS using InetAddress.getByAddress() factory method. This method can create addresses for hosts that do not exist or cannot be resolved:
public static InetAddress getByAddress(byte[] addr) throws UnknownHostException // creates an InetAddress object with an IP address and no hostname
public static InetAddress getByAddress(String hostname, byte[] addr) throws UnknownHostException // creates an InetAddress object with an IP address and a hostname.

byte[] addr = {107, 23, (byte) 216, (byte) 196}; // make an InetAddress for 107.23.216.196
InetAddress lessWrong = InetAddress.getByAddress(addr);
InetAddress lessWrongWithname = InetAddress.getByAddress("lesswrong.com", addr);
// Unlike the other factory methods, these two methods make no guarantees that such a host exists or that the hostname is correctly mapped to the IP address. They throw an UnknownHostException only if a byte array of an illegal size (neither 4 nor 16 bytes long) is passed as the address argument.

// Lookups by IP address:
// When you call getByName() WITH AN IP ADDRESS STRING AS AN ARGUMENT ("208.201.239.37", not "www.oreilly.com"), it creates an InetAddress object for the requested IP address without checking with DNS. This means it's possible to create InetAddress objects for hosts that don't really exist and that you can't connect to. The hostname of an InetAddress object created from a string containing an IP address is initially set to that string. A DNS lookup for the actual hostname is only performed when the hostname is requested, either explicitly via a getHostName() or implicitly by toString(). That's how www.oreilly.com was determined from the dotted quad address 208.201.239.37. If, at the time the hostname is requested and a DNS lookup is finally performed, the host with the specified IP address can't be found, the hostname remains the original dotted quad string. However, no UnknownHostException is thrown. Hostnames are much more stable than IP addresses. Some services have lived at the same hostname for years, but have switched IP addresses several times. If you have a choice between using a hostname an IP address, always choose the hostname. Use an IP address only when a hostname is not available.

// java.net.InetAddress overrides three methods of java.lang.Object to provide more specialized behavior:
public boolean equals(Object o)
// An object is equal to an InetAddress object only if it is itself an instance of the InetAddress class and it has the same IP address. It does not need to have the same hostname. Thus, an InetAddress object for www.ibiblio.org is equal to an InetAddress object for www.cafeaulait.org because both names refer to the same IP address.
public int hashCode()
// The hashCode() method is consistent with the equals() method. The int that hashCode() returns is calculated solely from the IP address. It does not take the hostname into account. If two InetAddress objects have the same address, then they have the same hash code, even if their hostnames are different.
public String toString()
// Returns a short text representation of the object in the format "hostname/dotted ip address".

// ******* The Socket Class:

// The term socket programming refers to writing programs that execute across multiple computers in which the devices are all connected to each other using a network. A socket is one endpoint of a two-way communication link between two programs running on different computers on a network. A socket is bound to a port number so that the transport layer can identify the application that data is destined to be sent to.

// >>> Read this first: https://www.codejava.net/java-se/networking/java-socket-server-examples-tcp-ip

// In the next example, Client keeps reading input from user and sends to the server until "Over" is typed.

// A Java program for a Client :
import java.net.*;
import java.io.*;

public class Client {
   private Socket socket = null;
   private DataInputStream dataInputStream = null;
   private DataOutputStream dataOutputStream = null;

   public Client(String address, int port)  {
      try {
         // To connect to other machine we need a socket connection. A socket connection means the two machines have information about each
         // other's network location (IP Address) and TCP port. The java.net.Socket class represents a Socket. Open a socket (establish a connection):
         socket = new Socket(address, port);
         System.out.println("Connected");

         // To communicate over a socket connection, streams are used to both input and output the data:
         dataInputStream = new DataInputStream(System.in); // takes input from terminal
         dataOutputStream = new DataOutputStream(socket.getOutputStream()); // sends output to the socket
      }
      catch (UnknownHostException u) {
         System.out.println(u);
      }
      catch (IOException i) {
         System.out.println(i);
      }

      // string to read message from input
      String line = "";

      // keep reading until "Over" is input
      while (!line.equals("Over")) {
         try {
            line = dataInputStream.readLine();
            dataOutputStream.writeUTF(line);
         }
         catch (IOException i)  {
            System.out.println(i);
         }
      }

      // close the connection
      try {
         dataInputStream.close();
         dataOutputStream.close();
         socket.close();
      }
      catch (IOException i)  {
         System.out.println(i);
      }
   }

   public static void main(String args[]) {
      Client client = new Client("127.0.0.1", 5000);
   }
}

// Server Programming
// To write a server application, two sockets are needed:
// A ServerSocket which waits for the client requests (when a client makes a new Socket())
// A plain old Socket to use for communication with the client.
// The java.net.Socket class represents the socket that both the client and the 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.

// A Java program for a Server:
import java.net.*;
import java.io.*;

public class Server {
   private Socket connectionSocket = null;
   private ServerSocket serverSocket = null;
   private DataInputStream dataInputStream = null;

   public Server(int port) {
      // Starts server and waits for a connection
      try {
         serverSocket = new ServerSocket(port);
         System.out.println("Server started");

         System.out.println("Waiting for a client ...");

         // Start listening for incoming client requests:
         connectionSocket = serverSocket.accept(); // the accept() method blocks (just sits there) until a client connects to the server; the connection is represented by the returned Socket object
         System.out.println("Client accepted");

         // Then we take input from the client using getInputStream() method. Our Server keeps receiving messages until the Client sends "Over":
         dataInputStream = new DataInputStream(new BufferedInputStream(connectionSocket.getInputStream()));

         String line = "";

         // Reads messages from client until "Over" is sent:
         while (!line.equals("Over")) {
            try {
               line = dataInputStream.readUTF();
               System.out.println(line);
            }
            catch (IOException i) {
               System.out.println(i);
            }
         }
         
         connectionSocket.close(); // terminate the connection with the client
         dataInputStream.close();
      }
      catch (IOException i)  {
         System.out.println(i);
      }
   }

   public static void main(String args[])  {
      Server server = new Server(5000);
   }
}

// ******* Multithreaded Server:

// File Name GreetingServer.java
import java.net.*;
import java.io.*;

public class GreetingServer extends Thread {
    private ServerSocket serverSocket;
   
    public GreetingServer(int port) throws IOException {
      serverSocket = new ServerSocket(port);
      serverSocket.setSoTimeout(10000);
    }

    public void run() {
      while (true) {
         try {
            System.out.println("Waiting for client on port " + serverSocket.getLocalPort() + "...");
            Socket connectionSocket = serverSocket.accept(); // wait until client connects or the timeout of 10000 milliseconds is over (it was set by setSoTimeout)

            System.out.println("Just connected to " + connectionSocket.getRemoteSocketAddress());
            DataInputStream dataInputStream = new DataInputStream(connectionSocket.getInputStream());

            System.out.println(dataInputStream.readUTF());
            DataOutputStream dataOutputStream = new DataOutputStream(connectionSocket.getOutputStream());
            dataOutputStream.writeUTF("Thank you for connecting to " + connectionSocket.getLocalSocketAddress()  + "\nGoodbye!");
            connectionSocket.close();
         } catch (SocketTimeoutException s) {
            System.out.println("Socket timed out!");
            break;
         } catch (IOException e) {
            e.printStackTrace();
            break;
         }
      }
   }
   
   public static void main(String [] args) {
      int port = Integer.parseInt(args[0]);
      try {
         Thread t = new GreetingServer(port);
         t.start();
      } catch (IOException e) {
         e.printStackTrace();
      }
   }
}
User avatar
Ursego
Site Admin
 
Posts: 143
Joined: 19 Feb 2013, 20:33



Ketones are a more high-octane fuel for your brain than glucose. Become a biohacker and upgrade yourself to version 2.0!



cron
Traffic Counter

eXTReMe Tracker