Subclass of MouseAdapter #Programming Code Examples #Java/J2EE/J2ME #Mouse and Keyboard Events

!!!!!!!!!!!!
ClickListener.java A simple subclass of MouseAdapter that reports where the mouse was pressed. When attached to an applet, look for the report in the Java Console.
!!!!!!!!!!!!
import java.awt.event.*;

/** The listener used by ClickReporter.
 *  

************** public class ClickListener extends MouseAdapter { public void mousePressed(MouseEvent event) { System.out.println("Mouse pressed at (" + event.getX() + "," + event.getY() + ")."); } } < <<<<<<<<<<<<<

Note: Brought from our old site: http://www.salearningschool.com/example_codes/ on Jan 2nd, 2017 From: http://sitestree.com/?p=10358
Categories:Programming Code Examples, Java/J2EE/J2ME, Mouse and Keyboard Events
Tags:Java/J2EE/J2MEMouse and Keyboard Events
Post Data:2017-01-02 16:04:35

Shop Online: https://www.ShopForSoul.com/
(Big Data, Cloud, Security, Machine Learning): Courses: http://Training.SitesTree.com
In Bengali: http://Bangla.SaLearningSchool.com
http://SitesTree.com
8112223 Canada Inc./JustEtc: http://JustEtc.net (Software/Web/Mobile/Big-Data/Machine Learning)
Shop Online: https://www.ShopForSoul.com/
Medium: https://medium.com/@SayedAhmedCanada

# RMI Example – Numerical Integration, a more realistic RMI example that sends an evaluatable object (function) from a client to a server for numerical integration. #Programming Code Examples #Java/J2EE/J2ME #Network Programming

# RMI Example - Numerical Integration, a more realistic RMI example that sends an evaluatable object (function) from a client to a server for numerical integration. 

Integral.java  Performs actual numerical integration of the function (evaluatable object).

/** A class to calculate summations and numeric integrals. The
 *  integral is calculated according to the midpoint rule.
 *
 *  Taken from Core Web Programming from
 *  Prentice Hall and Sun Microsystems Press,
 *  .
 *  © 2001 Marty Hall and Larry Brown;
 *  may be freely used or adapted.
 */

public class Integral {
  /** Returns the sum of f(x) from x=start to x=stop, where the
   *  function f is defined by the evaluate method of the
   *  Evaluatable object.
   */

  public static double sum(double start, double stop,
                           double stepSize,
                           Evaluatable evalObj) {
    double sum = 0.0, current = start;
    while (current  0) ? args[0] : "localhost";
      RemoteIntegral remoteIntegral =
        (RemoteIntegral)Naming.lookup("rmi://" + host +
                                      "/RemoteIntegral");
      for(int steps=10; steps 0) ? args[0] : "localhost";
      RemoteIntegral remoteIntegral =
        (RemoteIntegral)Naming.lookup("rmi://" + host +
                                      "/RemoteIntegral");
      for(int steps=10; steps< =10000; steps*=10) {
        System.out.println
          ("Approximated with " + steps + " steps:" +
           "n  Integral from 0 to pi of sin(x)=" +
           remoteIntegral.integrate(0.0, Math.PI,
                                    steps, new Sin()) +
           "n  Integral from pi/2 to pi of cos(x)=" +
           remoteIntegral.integrate(Math.PI/2.0, Math.PI,
                                    steps, new Cos()) +
           "n  Integral from 0 to 5 of x^2=" +
           remoteIntegral.integrate(0.0, 5.0, steps,
                                    new Quadratic()));
      }
      System.out.println
        ("`Correct' answer using Math library:" +
         "n  Integral from 0 to pi of sin(x)=" +
         (-Math.cos(Math.PI) - -Math.cos(0.0)) +
         "n  Integral from pi/2 to pi of cos(x)=" +
         (Math.sin(Math.PI) - Math.sin(Math.PI/2.0)) +
         "n  Integral from 0 to 5 of x^2=" +
         (Math.pow(5.0, 3.0) / 3.0));
    } catch(RemoteException re) {
      System.out.println("RemoteException: " + re);
    } catch(NotBoundException nbe) {
      System.out.println("NotBoundException: " + nbe);
    } catch(MalformedURLException mfe) {
      System.out.println("MalformedURLException: " + mfe);
    }
  }
}

rmiclient.policy  Policy file for the client. Grants permissions for the client to connect to the RMI server and Web server. 

//  Taken from Core Web Programming from
//  Prentice Hall and Sun Microsystems Press,
//  .
//  © 2001 Marty Hall and Larry Brown;
//  may be freely used or adapted.

grant {
  // rmihost - RMI registry and the server
  // webhost - HTTP server for stub classes
  permission java.net.SocketPermission 
    "rmihost:1024-65535", "connect";
  permission java.net.SocketPermission 
    "webhost:80", "connect";
};



Note: Brought from our old site: http://www.salearningschool.com/example_codes/ on Jan 2nd, 2017 From: http://sitestree.com/?p=10239
Categories:Programming Code Examples, Java/J2EE/J2ME, Network Programming
Tags:Java/J2EE/J2MENetwork Programming
Post Data:2017-01-02 16:04:28

Shop Online: https://www.ShopForSoul.com/
(Big Data, Cloud, Security, Machine Learning): Courses: http://Training.SitesTree.com
In Bengali: http://Bangla.SaLearningSchool.com
http://SitesTree.com
8112223 Canada Inc./JustEtc: http://JustEtc.net (Software/Web/Mobile/Big-Data/Machine Learning)
Shop Online: https://www.ShopForSoul.com/
Medium: https://medium.com/@SayedAhmedCanada

RMI Example – Message, illustrates retrieving a message from an object located on a remote server. Requires the following classes: #Programming Code Examples #Java/J2EE/J2ME #Network Programming

RMI Example - Message, illustrates retrieving a message from an object located on a remote server. Requires the following classes: 

Rem.java  Establishes which methods the client can access in the remote object. 





import java.rmi.*;

/** The RMI client will use this interface directly. The RMI
 *  server will make a real remote object that implements this,
 *  then register an instance of it with some URL.
 *
 *  Taken from Core Web Programming from
 *  Prentice Hall and Sun Microsystems Press,
 *  .
 *  © 2001 Marty Hall and Larry Brown;
 *  may be freely used or adapted.
 */

public interface Rem extends Remote {
  public String getMessage() throws RemoteException;
}


RemClient.java  The client application which communicates to the remote object and retrieves the message. 

import java.rmi.*; // For Naming, RemoteException, etc.
import java.net.*; // For MalformedURLException
import java.io.*;  // For Serializable interface

/** Get a Rem object from the specified remote host.
 *  Use its methods as though it were a local object.
 *
 *  Taken from Core Web Programming from
 *  Prentice Hall and Sun Microsystems Press,
 *  .
 *  © 2001 Marty Hall and Larry Brown;
 *  may be freely used or adapted.
 */

public class RemClient {
  public static void main(String[] args) {
    try {
      String host =
        (args.length > 0) ? args[0] : "localhost";
      // Get the remote object and store it in remObject:
      Rem remObject =
        (Rem)Naming.lookup("rmi://" + host + "/Rem");
      // Call methods in remObject:
      System.out.println(remObject.getMessage());
    } catch(RemoteException re) {
      System.out.println("RemoteException: " + re);
    } catch(NotBoundException nbe) {
      System.out.println("NotBoundException: " + nbe);
    } catch(MalformedURLException mfe) {
      System.out.println("MalformedURLException: " + mfe);
    }
  }
}


RemImpl.java  The concrete, remote object that implements the methods in Rem.java. 

import java.rmi.*;
import java.rmi.server.UnicastRemoteObject;

/** This is the actual implementation of Rem that the RMI
 *  server uses. The server builds an instance of this, then
 *  registers it with a URL. The client accesses the URL and
 *  binds the result to a Rem (not a RemImpl; it doesn't
 *  have this).
 *
 *  Taken from Core Web Programming from
 *  Prentice Hall and Sun Microsystems Press,
 *  .
 *  © 2001 Marty Hall and Larry Brown;
 *  may be freely used or adapted.
 */

public class RemImpl extends UnicastRemoteObject
                     implements Rem {
  public RemImpl() throws RemoteException {}

  public String getMessage() throws RemoteException {
    return("Here is a remote message.");
  }
}


RemServer.java  Creates an instance of RemImpl on the remote server and binds the object in the registry for lookup by the client. 

import java.rmi.*;
import java.net.*;

/** The server creates a RemImpl (which implements the Rem
 *  interface), then registers it with the URL Rem, where
 *  clients can access it.
 *
 *  Taken from Core Web Programming from
 *  Prentice Hall and Sun Microsystems Press,
 *  .
 *  © 2001 Marty Hall and Larry Brown;
 *  may be freely used or adapted.
 */

public class RemServer {
  public static void main(String[] args) {
    try {
      RemImpl localObject = new RemImpl();
      Naming.rebind("rmi:///Rem", localObject);
    } catch(RemoteException re) {
      System.out.println("RemoteException: " + re);
    } catch(MalformedURLException mfe) {
      System.out.println("MalformedURLException: " + mfe);
    }
  }
}


Note: Brought from our old site: http://www.salearningschool.com/example_codes/ on Jan 2nd, 2017 From: http://sitestree.com/?p=10238
Categories:Programming Code Examples, Java/J2EE/J2ME, Network Programming
Tags:Java/J2EE/J2MENetwork Programming
Post Data:2017-01-02 16:04:28

Shop Online: https://www.ShopForSoul.com/
(Big Data, Cloud, Security, Machine Learning): Courses: http://Training.SitesTree.com
In Bengali: http://Bangla.SaLearningSchool.com
http://SitesTree.com
8112223 Canada Inc./JustEtc: http://JustEtc.net (Software/Web/Mobile/Big-Data/Machine Learning)
Shop Online: https://www.ShopForSoul.com/
Medium: https://medium.com/@SayedAhmedCanada

ThreadedEchoServer.java A multithreaded version of EchoServer, where each client request is serviced on a separate thread. Requires the following classes: #Programming Code Examples #Java/J2EE/J2ME #Network Programming

ThreadedEchoServer.java  A multithreaded version of EchoServer, where each client request is serviced on a separate thread. Requires the following classes: 


import java.net.*;
import java.io.*;

/** A multithreaded variation of EchoServer.
 *
 *  Taken from Core Web Programming from
 *  Prentice Hall and Sun Microsystems Press,
 *  .
 *  © 2001 Marty Hall and Larry Brown;
 *  may be freely used or adapted.
 */

public class ThreadedEchoServer extends EchoServer
                                implements Runnable {
  public static void main(String[] args) {
    int port = 8088;
    if (args.length > 0) {
      try {
        port = Integer.parseInt(args[0]);
      } catch(NumberFormatException nfe) {}
    }
    ThreadedEchoServer echoServer =
      new ThreadedEchoServer(port, 0);
    echoServer.serverName = "Threaded EchoServer";
  }

  public ThreadedEchoServer(int port, int connections) {
    super(port, connections);
  }

  /** The new version of handleConnection starts a thread. This
   *  new thread will call back to the old version of
   *  handleConnection, resulting in the same server behavior
   *  in a multithreaded version. The thread stores the Socket
   *  instance since run doesn't take any arguments, and since
   *  storing the socket in an instance variable risks having
   *  it overwritten if the next thread starts before the run
   *  method gets a chance to copy the socket reference.
   */

  public void handleConnection(Socket server) {
    Connection connectionThread = new Connection(this, server);
    connectionThread.start();
  }

  public void run() {
    Connection currentThread =
      (Connection)Thread.currentThread();
    try {
      super.handleConnection(currentThread.getSocket());
    } catch(IOException ioe) {
      System.out.println("IOException: " + ioe);
      ioe.printStackTrace();
    }
  }
}

/** This is just a Thread with a field to store a Socket object.
 *  Used as a thread-safe means to pass the Socket from
 *  handleConnection to run.
 */

class Connection extends Thread {
  private Socket serverSocket;

  public Connection(Runnable serverObject,
                    Socket serverSocket) {
    super(serverObject);
    this.serverSocket = serverSocket;
  }

  public Socket getSocket() {
    return serverSocket;
  }
}



EchoServer.java  Creates a Web page showing all data sent from the client (browser). 


import java.net.*;
import java.io.*;
import java.util.StringTokenizer;

/** A simple HTTP server that generates a Web page showing all
 *  of the data that it received from the Web client (usually
 *  a browser). To use this server, start it on the system of
 *  your choice, supplying a port number if you want something
 *  other than port 8088. Call this system server.com. Next,
 *  start a Web browser on the same or a different system, and
 *  connect to http://server.com:8088/whatever. The resultant
 *  Web page will show the data that your browser sent. For 
 *  debugging in servlet or CGI programming, specify 
 *  http://server.com:8088/whatever as the ACTION of your HTML
 *  form. You can send GET or POST data; either way, the
 *  resultant page will show what your browser sent.
 *
 *  Taken from Core Web Programming from 
 *  Prentice Hall and Sun Microsystems Press,
 *  © 2001 Marty Hall and Larry Brown;
 *  may be freely used or adapted. 
 */

public class EchoServer extends NetworkServer {
  protected int maxRequestLines = 50;
  protected String serverName = "EchoServer";

  /** Supply a port number as a command-line
   *  argument. Otherwise, use port 8088.
   */
  
  public static void main(String[] args) {
    int port = 8088;
    if (args.length > 0) {
      try {
        port = Integer.parseInt(args[0]);
      } catch(NumberFormatException nfe) {}
    }
    new EchoServer(port, 0);
  }

  public EchoServer(int port, int maxConnections) {
    super(port, maxConnections);
    listen();
  }

  /** Overrides the NetworkServer handleConnection method to 
   *  read each line of data received, save it into an array
   *  of strings, then send it back embedded inside a PRE 
   *  element in an HTML page.
   */
  
  public void handleConnection(Socket server)
      throws IOException{
    System.out.println
        (serverName + ": got connection from " +
         server.getInetAddress().getHostName());
    BufferedReader in = SocketUtil.getReader(server);
    PrintWriter out = SocketUtil.getWriter(server);
    String[] inputLines = new String[maxRequestLines];
    int i;
    for (i=0; i<maxrequestlines ; i++) {
      inputLines[i] = in.readLine();
      if (inputLines[i] == null) // Client closed connection.
        break;
      if (inputLines[i].length() == 0) { // Blank line.
        if (usingPost(inputLines)) {
          readPostData(inputLines, i, in);
          i = i + 2;
        }
        break;
      }
    }
    printHeader(out);
    for (int j=0; j<i; j++) {
      out.println(inputLines[j]);
    }
    printTrailer(out);
    server.close();
  }

  // Send standard HTTP response and top of a standard Web page.
  // Use HTTP 1.0 for compatibility with all clients.
  
  private void printHeader(PrintWriter out) {
    out.println
      ("HTTP/1.0 200 OKrn" +
       "Server: " + serverName + "rn" +
       "Content-Type: text/htmlrn" +
       "rn" +
       "n" +
       "n" +
       "n" +
       "  " + serverName + " Resultsn" +
       "n" +
       "n" +
       "n" +
       "

" + serverName + " Results

n" + "Here is the request line and request headersn" + "sent by your browser:n" + "
");
  }

  // Print bottom of a standard Web page.
  
  private void printTrailer(PrintWriter out) {
    out.println
      ("

n" +
"n" +
"n");
}

// Normal Web page requests use GET, so this server can simply
// read a line at a time. However, HTML forms can also use
// POST, in which case we have to determine the number of POST
// bytes that are sent so we know how much extra data to read
// after the standard HTTP headers.

private boolean usingPost(String[] inputs) {
return(inputs[0].toUpperCase().startsWith("POST"));
}

private void readPostData(String[] inputs, int i,
BufferedReader in)
throws IOException {
int contentLength = contentLength(inputs);
char[] postData = new char[contentLength];
in.read(postData, 0, contentLength);
inputs[++i] = new String(postData, 0, contentLength);
}

// Given a line that starts with Content-Length,
// this returns the integer value specified.

private int contentLength(String[] inputs) {
String input;
for (int i=0; i<inputs .length; i++) {
if (inputs[i].length() == 0)
break;
input = inputs[i].toUpperCase();
if (input.startsWith("CONTENT-LENGTH"))
return(getLength(input));
}
return(0);
}

private int getLength(String length) {
StringTokenizer tok = new StringTokenizer(length);
tok.nextToken();
return(Integer.parseInt(tok.nextToken()));
}
}

NetworkServer.java A starting point for network servers.

import java.net.*;
import java.io.*;

/** A starting point for network servers. You'll need to
* override handleConnection, but in many cases listen can
* remain unchanged. NetworkServer uses SocketUtil to simplify
* the creation of the PrintWriter and BufferedReader.
*
* Taken from Core Web Programming from
* Prentice Hall and Sun Microsystems Press,
* .
* © 2001 Marty Hall and Larry Brown;
* may be freely used or adapted.
*/

public class NetworkServer {
private int port, maxConnections;

/** Build a server on specified port. It will continue to
* accept connections, passing each to handleConnection until
* an explicit exit command is sent (e.g., System.exit) or
* the maximum number of connections is reached. Specify
* 0 for maxConnections if you want the server to run
* indefinitely.
*/

public NetworkServer(int port, int maxConnections) {
setPort(port);
setMaxConnections(maxConnections);
}

/** Monitor a port for connections. Each time one is
* established, pass resulting Socket to handleConnection.
*/

public void listen() {
int i=0;
try {
ServerSocket listener = new ServerSocket(port);
Socket server;
while((i++ < maxConnections) || (maxConnections == 0)) {
server = listener.accept();
handleConnection(server);
}
} catch (IOException ioe) {
System.out.println("IOException: " + ioe);
ioe.printStackTrace();
}
}

/** This is the method that provides the behavior to the
* server, since it determines what is done with the
* resulting socket. Override this method in servers
* you write.
*

* This generic version simply reports the host that made
* the connection, shows the first line the client sent,
* and sends a single line in response.
*/

protected void handleConnection(Socket server)
throws IOException{
BufferedReader in = SocketUtil.getReader(server);
PrintWriter out = SocketUtil.getWriter(server);
System.out.println
("Generic Network Server: got connection from " +
server.getInetAddress().getHostName() + "n" +
"with first line ‘" + in.readLine() + "’");
out.println("Generic Network Server");
server.close();
}

/** Gets the max connections server will handle before
* exiting. A value of 0 indicates that server should run
* until explicitly killed.
*/

public int getMaxConnections() {
return(maxConnections);
}

/** Sets max connections. A value of 0 indicates that server
* should run indefinitely (until explicitly killed).
*/

public void setMaxConnections(int maxConnections) {
this.maxConnections = maxConnections;
}

/** Gets port on which server is listening. */

public int getPort() {
return(port);
}

/** Sets port. You can only do before "connect" is
* called.
That usually happens in the constructor.
*/

protected void setPort(int port) {
this.port = port;
}
}

SocketUtil.java Simplifies the creation of a PrintWriter and BufferedReader.

import java.net.*;
import java.io.*;

/** A shorthand way to create BufferedReaders and
* PrintWriters associated with a Socket.
*
* Taken from Core Web Programming from
* Prentice Hall and Sun Microsystems Press,
* © 2001 Marty Hall and Larry Brown;
* may be freely used or adapted.
*/

public class SocketUtil {
/** Make a BufferedReader to get incoming data. */

public static BufferedReader getReader(Socket s)
throws IOException {
return(new BufferedReader(
new InputStreamReader(s.getInputStream())));
}

/** Make a PrintWriter to send outgoing data.
* This PrintWriter will automatically flush stream
* when println is called.
*/

public static PrintWriter getWriter(Socket s)
throws IOException {
// Second argument of true means autoflush.
return(new PrintWriter(s.getOutputStream(), true));
}
}

Note: Brought from our old site: http://www.salearningschool.com/example_codes/ on Jan 2nd, 2017 From: http://sitestree.com/?p=10237
Categories:Programming Code Examples, Java/J2EE/J2ME, Network Programming
Tags:Java/J2EE/J2MENetwork Programming
Post Data:2017-01-02 16:04:28

Shop Online: https://www.ShopForSoul.com/
(Big Data, Cloud, Security, Machine Learning): Courses: http://Training.SitesTree.com
In Bengali: http://Bangla.SaLearningSchool.com
http://SitesTree.com
8112223 Canada Inc./JustEtc: http://JustEtc.net (Software/Web/Mobile/Big-Data/Machine Learning)
Shop Online: https://www.ShopForSoul.com/
Medium: https://medium.com/@SayedAhmedCanada

EchoServer.java A simple HTTP server that creates a Web page showing all data sent from the client (browser), including all HTTP request headers sent form the client. Uses the following classes: #Programming Code Examples #Java/J2EE/J2ME #Network Programming

EchoServer.java  A simple HTTP server that creates a Web page showing all data sent from the client (browser), including all HTTP request headers sent form the client. Uses the following classes: 

import java.net.*;
import java.io.*;
import java.util.StringTokenizer;

/** A simple HTTP server that generates a Web page showing all
 *  of the data that it received from the Web client (usually
 *  a browser). To use this server, start it on the system of
 *  your choice, supplying a port number if you want something
 *  other than port 8088. Call this system server.com. Next,
 *  start a Web browser on the same or a different system, and
 *  connect to http://server.com:8088/whatever. The resultant
 *  Web page will show the data that your browser sent. For
 *  debugging in servlet or CGI programming, specify
 *  http://server.com:8088/whatever as the ACTION of your HTML
 *  form. You can send GET or POST data; either way, the
 *  resultant page will show what your browser sent.
 *
 *  Taken from Core Web Programming from
 *  Prentice Hall and Sun Microsystems Press,
 *  .
 *  © 2001 Marty Hall and Larry Brown;
 *  may be freely used or adapted.
 */

public class EchoServer extends NetworkServer {
  protected int maxRequestLines = 50;
  protected String serverName = "EchoServer";

  /** Supply a port number as a command-line
   *  argument. Otherwise, use port 8088.
   */

  public static void main(String[] args) {
    int port = 8088;
    if (args.length > 0) {
      try {
        port = Integer.parseInt(args[0]);
      } catch(NumberFormatException nfe) {}
    }
    new EchoServer(port, 0);
  }

  public EchoServer(int port, int maxConnections) {
    super(port, maxConnections);
    listen();
  }

  /** Overrides the NetworkServer handleConnection method to
   *  read each line of data received, save it into an array
   *  of strings, then send it back embedded inside a PRE
   *  element in an HTML page.
   */

  public void handleConnection(Socket server)
      throws IOException{
    System.out.println
        (serverName + ": got connection from " +
         server.getInetAddress().getHostName());
    BufferedReader in = SocketUtil.getReader(server);
    PrintWriter out = SocketUtil.getWriter(server);
    String[] inputLines = new String[maxRequestLines];
    int i;
    for (i=0; i<maxrequestlines ; i++) {
      inputLines[i] = in.readLine();
      if (inputLines[i] == null) // Client closed connection.
        break;
      if (inputLines[i].length() == 0) { // Blank line.
        if (usingPost(inputLines)) {
          readPostData(inputLines, i, in);
          i = i + 2;
        }
        break;
      }
    }
    printHeader(out);
    for (int j=0; j<i; j++) {
      out.println(inputLines[j]);
    }
    printTrailer(out);
    server.close();
  }

  // Send standard HTTP response and top of a standard Web page.
  // Use HTTP 1.0 for compatibility with all clients.

  private void printHeader(PrintWriter out) {
    out.println
      ("HTTP/1.0 200 OKrn" +
       "Server: " + serverName + "rn" +
       "Content-Type: text/htmlrn" +
       "rn" +
       "n" +
       "n" +
       "n" +
       "  " + serverName + " Resultsn" +
       "n" +
       "n" +
       "n" +
       "

" + serverName + " Results

n" + "Here is the request line and request headersn" + "sent by your browser:n" + "
");
  }

  // Print bottom of a standard Web page.

  private void printTrailer(PrintWriter out) {
    out.println
      ("

n" +
"n" +
"n");
}

// Normal Web page requests use GET, so this server can simply
// read a line at a time. However, HTML forms can also use
// POST, in which case we have to determine the number of POST
// bytes that are sent so we know how much extra data to read
// after the standard HTTP headers.

private boolean usingPost(String[] inputs) {
return(inputs[0].toUpperCase().startsWith("POST"));
}

private void readPostData(String[] inputs, int i,
BufferedReader in)
throws IOException {
int contentLength = contentLength(inputs);
char[] postData = new char[contentLength];
in.read(postData, 0, contentLength);
inputs[++i] = new String(postData, 0, contentLength);
}

// Given a line that starts with Content-Length,
// this returns the integer value specified.

private int contentLength(String[] inputs) {
String input;
for (int i=0; i<inputs .length; i++) {
if (inputs[i].length() == 0)
break;
input = inputs[i].toUpperCase();
if (input.startsWith("CONTENT-LENGTH"))
return(getLength(input));
}
return(0);
}

private int getLength(String length) {
StringTokenizer tok = new StringTokenizer(length);
tok.nextToken();
return(Integer.parseInt(tok.nextToken()));
}
}

NetworkServer.java A starting point for network servers.

import java.net.*;
import java.io.*;

/** A starting point for network servers. You'll need to
* override handleConnection, but in many cases listen can
* remain unchanged. NetworkServer uses SocketUtil to simplify
* the creation of the PrintWriter and BufferedReader.
*
* Taken from Core Web Programming from
* Prentice Hall and Sun Microsystems Press,
* .
* © 2001 Marty Hall and Larry Brown;
* may be freely used or adapted.
*/

public class NetworkServer {
private int port, maxConnections;

/** Build a server on specified port. It will continue to
* accept connections, passing each to handleConnection until
* an explicit exit command is sent (e.g., System.exit) or
* the maximum number of connections is reached. Specify
* 0 for maxConnections if you want the server to run
* indefinitely.
*/

public NetworkServer(int port, int maxConnections) {
setPort(port);
setMaxConnections(maxConnections);
}

/** Monitor a port for connections. Each time one is
* established, pass resulting Socket to handleConnection.
*/

public void listen() {
int i=0;
try {
ServerSocket listener = new ServerSocket(port);
Socket server;
while((i++ < maxConnections) || (maxConnections == 0)) {
server = listener.accept();
handleConnection(server);
}
} catch (IOException ioe) {
System.out.println("IOException: " + ioe);
ioe.printStackTrace();
}
}

/** This is the method that provides the behavior to the
* server, since it determines what is done with the
* resulting socket. Override this method in servers
* you write.
*

* This generic version simply reports the host that made
* the connection, shows the first line the client sent,
* and sends a single line in response.
*/

protected void handleConnection(Socket server)
throws IOException{
BufferedReader in = SocketUtil.getReader(server);
PrintWriter out = SocketUtil.getWriter(server);
System.out.println
("Generic Network Server: got connection from " +
server.getInetAddress().getHostName() + "n" +
"with first line ‘" + in.readLine() + "’");
out.println("Generic Network Server");
server.close();
}

/** Gets the max connections server will handle before
* exiting. A value of 0 indicates that server should run
* until explicitly killed.
*/

public int getMaxConnections() {
return(maxConnections);
}

/** Sets max connections. A value of 0 indicates that server
* should run indefinitely (until explicitly killed).
*/

public void setMaxConnections(int maxConnections) {
this.maxConnections = maxConnections;
}

/** Gets port on which server is listening. */

public int getPort() {
return(port);
}

/** Sets port. You can only do before "connect" is
* called.
That usually happens in the constructor.
*/

protected void setPort(int port) {
this.port = port;
}
}

SocketUtil.java Simplifies the creation of a PrintWriter and BufferedReader.

import java.net.*;
import java.io.*;

/** A shorthand way to create BufferedReaders and
* PrintWriters associated with a Socket.
*
* Taken from Core Web Programming from
* Prentice Hall and Sun Microsystems Press,
* © 2001 Marty Hall and Larry Brown;
* may be freely used or adapted.
*/

public class SocketUtil {
/** Make a BufferedReader to get incoming data. */

public static BufferedReader getReader(Socket s)
throws IOException {
return(new BufferedReader(
new InputStreamReader(s.getInputStream())));
}

/** Make a PrintWriter to send outgoing data.
* This PrintWriter will automatically flush stream
* when println is called.
*/

public static PrintWriter getWriter(Socket s)
throws IOException {
// Second argument of true means autoflush.
return(new PrintWriter(s.getOutputStream(), true));
}
}

Note: Brought from our old site: http://www.salearningschool.com/example_codes/ on Jan 2nd, 2017 From: http://sitestree.com/?p=10236
Categories:Programming Code Examples, Java/J2EE/J2ME, Network Programming
Tags:Java/J2EE/J2MENetwork Programming
Post Data:2017-01-02 16:04:28

Shop Online: https://www.ShopForSoul.com/
(Big Data, Cloud, Security, Machine Learning): Courses: http://Training.SitesTree.com
In Bengali: http://Bangla.SaLearningSchool.com
http://SitesTree.com
8112223 Canada Inc./JustEtc: http://JustEtc.net (Software/Web/Mobile/Big-Data/Machine Learning)
Shop Online: https://www.ShopForSoul.com/
Medium: https://medium.com/@SayedAhmedCanada

Implementing a Server : Network Server #Programming Code Examples #Java/J2EE/J2ME #Network Programming

NetworkServerTest.java  Establishes a network Server that listens for client requests on the port specified (command-line argument). Uses the following classes: 


/** Taken from Core Web Programming from
 *  Prentice Hall and Sun Microsystems Press,
 *  .
 *  © 2001 Marty Hall and Larry Brown;
 *  may be freely used or adapted.
 */


public class NetworkServerTest {
  public static void main(String[] args) {
    int port = 8088;
    if (args.length > 0) {
      port = Integer.parseInt(args[0]);
    }
    NetworkServer nwServer = new NetworkServer(port, 1);
    nwServer.listen();
  }
}


# NetworkServer.java  A starting point for network servers. 

import java.net.*;
import java.io.*;

/** A starting point for network servers. You'll need to
 *  override handleConnection, but in many cases listen can
 *  remain unchanged. NetworkServer uses SocketUtil to simplify
 *  the creation of the PrintWriter and BufferedReader.
 *
 *  Taken from Core Web Programming from
 *  Prentice Hall and Sun Microsystems Press,
 *  .
 *  © 2001 Marty Hall and Larry Brown;
 *  may be freely used or adapted.
 */

public class NetworkServer {
  private int port, maxConnections;

  /** Build a server on specified port. It will continue to
   *  accept connections, passing each to handleConnection until
   *  an explicit exit command is sent (e.g., System.exit) or
   *  the maximum number of connections is reached. Specify
   *  0 for maxConnections if you want the server to run
   *  indefinitely.
   */

  public NetworkServer(int port, int maxConnections) {
    setPort(port);
    setMaxConnections(maxConnections);
  }

  /** Monitor a port for connections. Each time one is
   *  established, pass resulting Socket to handleConnection.
   */

  public void listen() {
    int i=0;
    try {
      ServerSocket listener = new ServerSocket(port);
      Socket server;
      while((i++ < maxConnections) || (maxConnections == 0)) {
        server = listener.accept();
        handleConnection(server);
      }
    } catch (IOException ioe) {
      System.out.println("IOException: " + ioe);
      ioe.printStackTrace();
    }
  }

  /** This is the method that provides the behavior to the
   *  server, since it determines what is done with the
   *  resulting socket. Override this method in servers
   *  you write.
   *  

* This generic version simply reports the host that made * the connection, shows the first line the client sent, * and sends a single line in response. */ protected void handleConnection(Socket server) throws IOException{ BufferedReader in = SocketUtil.getReader(server); PrintWriter out = SocketUtil.getWriter(server); System.out.println ("Generic Network Server: got connection from " + server.getInetAddress().getHostName() + "n" + "with first line '" + in.readLine() + "'"); out.println("Generic Network Server"); server.close(); } /** Gets the max connections server will handle before * exiting. A value of 0 indicates that server should run * until explicitly killed. */ public int getMaxConnections() { return(maxConnections); } /** Sets max connections. A value of 0 indicates that server * should run indefinitely (until explicitly killed). */ public void setMaxConnections(int maxConnections) { this.maxConnections = maxConnections; } /** Gets port on which server is listening. */ public int getPort() { return(port); } /** Sets port. You can only do before "connect" is * called. That usually happens in the constructor. */ protected void setPort(int port) { this.port = port; } } SocketUtil.java Simplifies the creation of a PrintWriter and BufferedReader. import java.net.*; import java.io.*; /** A shorthand way to create BufferedReaders and * PrintWriters associated with a Socket. * * Taken from Core Web Programming from * Prentice Hall and Sun Microsystems Press, * © 2001 Marty Hall and Larry Brown; * may be freely used or adapted. */ public class SocketUtil { /** Make a BufferedReader to get incoming data. */ public static BufferedReader getReader(Socket s) throws IOException { return(new BufferedReader( new InputStreamReader(s.getInputStream()))); } /** Make a PrintWriter to send outgoing data. * This PrintWriter will automatically flush stream * when println is called. */ public static PrintWriter getWriter(Socket s) throws IOException { // Second argument of true means autoflush. return(new PrintWriter(s.getOutputStream(), true)); } }

Note: Brought from our old site: http://www.salearningschool.com/example_codes/ on Jan 2nd, 2017 From: http://sitestree.com/?p=10235
Categories:Programming Code Examples, Java/J2EE/J2ME, Network Programming
Tags:Java/J2EE/J2MENetwork Programming
Post Data:2017-01-02 16:04:28

Shop Online: https://www.ShopForSoul.com/
(Big Data, Cloud, Security, Machine Learning): Courses: http://Training.SitesTree.com
In Bengali: http://Bangla.SaLearningSchool.com
http://SitesTree.com
8112223 Canada Inc./JustEtc: http://JustEtc.net (Software/Web/Mobile/Big-Data/Machine Learning)
Shop Online: https://www.ShopForSoul.com/
Medium: https://medium.com/@SayedAhmedCanada

WebClient – Client application that can talk interactively to Web servers. Requires the components listed below #Programming Code Examples #Java/J2EE/J2ME #Network Programming

WebClient - Client application that can talk interactively to Web servers. Requires the components listed below

import java.awt.*; // For BorderLayout, GridLayout, Font, Color.
import java.awt.event.*;
import java.util.*;
import javax.swing.*;

/** A graphical client that lets you interactively connect to
 *  Web servers and send custom request lines and
 *  request headers.
 *
 *  Taken from Core Web Programming from
 *  Prentice Hall and Sun Microsystems Press,
 *  .
 *  © 2001 Marty Hall and Larry Brown;
 *  may be freely used or adapted.
 */

public class WebClient extends JPanel
    implements Runnable, Interruptible, ActionListener {
  public static void main(String[] args) {
    WindowUtilities.setNativeLookAndFeel();
    WindowUtilities.openInJFrame(new WebClient(), 600, 700,
                                 "Web Client",
                                 SystemColor.control);
  }

  private LabeledTextField hostField, portField,
          requestLineField;
  private JTextArea requestHeadersArea, resultArea;
  private String host, requestLine;
  private int port;
  private String[] requestHeaders = new String[30];
  private JButton submitButton, interruptButton;
  private boolean isInterrupted = false;

  public WebClient() {
    setLayout(new BorderLayout(5, 30));
    int fontSize = 14;
    Font labelFont =
      new Font("Serif", Font.BOLD, fontSize);
    Font headingFont =
      new Font("SansSerif", Font.BOLD, fontSize+4);
    Font textFont =
      new Font("Monospaced", Font.BOLD, fontSize-2);
    JPanel inputPanel = new JPanel();
    inputPanel.setLayout(new BorderLayout());
    JPanel labelPanel = new JPanel();
    labelPanel.setLayout(new GridLayout(4,1));
    hostField = new LabeledTextField("Host:", labelFont,
                                     30, textFont);
    portField = new LabeledTextField("Port:", labelFont,
                                     "80", 5, textFont);
    // Use HTTP 1.0 for compatibility with the most servers.
    // If you switch this to 1.1, you *must* supply a
    // Host: request header.
    requestLineField =
      new LabeledTextField("Request Line:", labelFont,
                           "GET / HTTP/1.0", 50, textFont);
    labelPanel.add(hostField);
    labelPanel.add(portField);
    labelPanel.add(requestLineField);
    JLabel requestHeadersLabel =
      new JLabel("Request Headers:");
    requestHeadersLabel.setFont(labelFont);
    labelPanel.add(requestHeadersLabel);
    inputPanel.add(labelPanel, BorderLayout.NORTH);
    requestHeadersArea = new JTextArea(5, 80);
    requestHeadersArea.setFont(textFont);
    JScrollPane headerScrollArea =
      new JScrollPane(requestHeadersArea);
    inputPanel.add(headerScrollArea, BorderLayout.CENTER);
    JPanel buttonPanel = new JPanel();
    submitButton = new JButton("Submit Request");
    submitButton.addActionListener(this);
    submitButton.setFont(labelFont);
    buttonPanel.add(submitButton);
    inputPanel.add(buttonPanel, BorderLayout.SOUTH);
    add(inputPanel, BorderLayout.NORTH);
    JPanel resultPanel = new JPanel();
    resultPanel.setLayout(new BorderLayout());
    JLabel resultLabel =
      new JLabel("Results", JLabel.CENTER);
    resultLabel.setFont(headingFont);
    resultPanel.add(resultLabel, BorderLayout.NORTH);
    resultArea = new JTextArea();
    resultArea.setFont(textFont);
    JScrollPane resultScrollArea =
      new JScrollPane(resultArea);
    resultPanel.add(resultScrollArea, BorderLayout.CENTER);
    JPanel interruptPanel = new JPanel();
    interruptButton = new JButton("Interrupt Download");
    interruptButton.addActionListener(this);
    interruptButton.setFont(labelFont);
    interruptPanel.add(interruptButton);
    resultPanel.add(interruptPanel, BorderLayout.SOUTH);
    add(resultPanel, BorderLayout.CENTER);
  }

  public void actionPerformed(ActionEvent event) {
    if (event.getSource() == submitButton) {
      Thread downloader = new Thread(this);
      downloader.start();
    } else if (event.getSource() == interruptButton) {
      isInterrupted = true;
    }
  }

  public void run() {
    isInterrupted = false;
    if (hasLegalArgs())
      new HttpClient(host, port, requestLine,
		     requestHeaders, resultArea, this);
  }

  public boolean isInterrupted() {
    return(isInterrupted);
  }

  private boolean hasLegalArgs() {
    host = hostField.getTextField().getText();
    if (host.length() == 0) {
      report("Missing hostname");
      return(false);
    }
    String portString =
      portField.getTextField().getText();
    if (portString.length() == 0) {
      report("Missing port number");
      return(false);
    }
    try {
      port = Integer.parseInt(portString);
    } catch(NumberFormatException nfe) {
      report("Illegal port number: " + portString);
      return(false);
    }
    requestLine =
      requestLineField.getTextField().getText();
    if (requestLine.length() == 0) {
      report("Missing request line");
      return(false);
    }
    getRequestHeaders();
    return(true);
  }

  private void report(String s) {
    resultArea.setText(s);
  }

  private void getRequestHeaders() {
    for(int i=0; i<requestheaders .length; i++) {
      requestHeaders[i] = null;
    }
    int headerNum = 0;
    String header =
      requestHeadersArea.getText();
    StringTokenizer tok =
      new StringTokenizer(header, "rn");
    while (tok.hasMoreTokens()) {
      requestHeaders[headerNum++] = tok.nextToken();
    }
  }
}


HttpClient.java  Handles the underlying network communication. 

import java.net.*;
import java.io.*;
import javax.swing.*;

/** The underlying network client used by WebClient.
 *
 *  Taken from Core Web Programming from
 *  Prentice Hall and Sun Microsystems Press,
 *  .
 *  © 2001 Marty Hall and Larry Brown;
 *  may be freely used or adapted.
 */

public class HttpClient extends NetworkClient {
  private String requestLine;
  private String[] requestHeaders;
  private JTextArea outputArea;
  private Interruptible app;

  public HttpClient(String host, int port,
                    String requestLine, String[] requestHeaders,
                    JTextArea outputArea, Interruptible app) {
    super(host, port);
    this.requestLine = requestLine;
    this.requestHeaders = requestHeaders;
    this.outputArea = outputArea;
    this.app = app;
    if (checkHost(host)) {
      connect();
    }
  }

  protected void handleConnection(Socket uriSocket)
      throws IOException {
    try {
      PrintWriter out = SocketUtil.getWriter(uriSocket);
      BufferedReader in = SocketUtil.getReader(uriSocket);
      outputArea.setText("");
      out.println(requestLine);
      for(int i=0; i<requestHeaders.length; i++) {
        if (requestHeaders[i] == null) {
          break;
        } else {
          out.println(requestHeaders[i]);
        }
      }
      out.println();
      String line;
      while ((line = in.readLine()) != null &&
             !app.isInterrupted()) {
        outputArea.append(line + "n");
      }
      if (app.isInterrupted()) {
        outputArea.append("---- Download Interrupted ----");
      }
    } catch(Exception e) {
      outputArea.setText("Error: " + e);
    }
  }

  private boolean checkHost(String host) {
    try {
      InetAddress.getByName(host);
      return(true);
    } catch(UnknownHostException uhe) {
      outputArea.setText("Bogus host: " + host);
      return(false);
    }
  }
}


LabeledTextField.java  A labeled text field for the WebClient graphical user interface.

import java.awt.*; // For FlowLayout, Font.
import javax.swing.*;

/** A TextField with an associated Label.
 *
 *  Taken from Core Web Programming from
 *  Prentice Hall and Sun Microsystems Press,
 *  .
 *  © 2001 Marty Hall and Larry Brown;
 *  may be freely used or adapted.
 */

public class LabeledTextField extends JPanel {
  private JLabel label;
  private JTextField textField;

  public LabeledTextField(String labelString,
                          Font labelFont,
                          int textFieldSize,
                          Font textFont) {
    setLayout(new FlowLayout(FlowLayout.LEFT));
    label = new JLabel(labelString, JLabel.RIGHT);
    if (labelFont != null) {
      label.setFont(labelFont);
    }
    add(label);
    textField = new JTextField(textFieldSize);
    if (textFont != null) {
      textField.setFont(textFont);
    }
    add(textField);
  }

  public LabeledTextField(String labelString,
                          String textFieldString) {
    this(labelString, null, textFieldString,
         textFieldString.length(), null);
  }

  public LabeledTextField(String labelString,
                          int textFieldSize) {
    this(labelString, null, textFieldSize, null);
  }

  public LabeledTextField(String labelString,
                          Font labelFont,
                          String textFieldString,
                          int textFieldSize,
                          Font textFont) {
    this(labelString, labelFont,
         textFieldSize, textFont);
    textField.setText(textFieldString);
  }

  /** The Label at the left side of the LabeledTextField.
   *  To manipulate the Label, do:
   *  
   *    LabeledTextField ltf = new LabeledTextField(...);
   *    ltf.getLabel().someLabelMethod(...);
   *  

*/

public JLabel getLabel() {
return(label);
}

/** The TextField at the right side of the
* LabeledTextField.
*/

public JTextField getTextField() {
return(textField);
}
}

Interruptible.java Polls to see if the user choose to interrupt the current network download.

/** An interface for classes that can be polled to see
* if they’ve been interrupted. Used by HttpClient
* and WebClient to allow the user to interrupt a network
* download.
*
* Taken from Core Web Programming from
* Prentice Hall and Sun Microsystems Press,
* .
* © 2001 Marty Hall and Larry Brown;
* may be freely used or adapted.
*/

public interface Interruptible {
public boolean isInterrupted();
}

NetworkClient.java Starting point for a network client to communicate with a remote computer.

import java.net.*;
import java.io.*;

/** A starting point for network clients. You’ll need to
* override handleConnection, but in many cases connect can
* remain unchanged. It uses SocketUtil to simplify the
* creation of the PrintWriter and BufferedReader.
*
* Taken from Core Web Programming from
* Prentice Hall and Sun Microsystems Press,
* © 2001 Marty Hall and Larry Brown;
* may be freely used or adapted.
*/

public class NetworkClient {
protected String host;
protected int port;

/** Register host and port. The connection won’t
* actually be established until you call
* connect.
*/

public NetworkClient(String host, int port) {
this.host = host;
this.port = port;
}

/** Establishes the connection, then passes the socket
* to handleConnection.
*/

public void connect() {
try {
Socket client = new Socket(host, port);
handleConnection(client);
} catch(UnknownHostException uhe) {
System.out.println("Unknown host: " + host);
uhe.printStackTrace();
} catch(IOException ioe) {
System.out.println("IOException: " + ioe);
ioe.printStackTrace();
}
}

/** This is the method you will override when
* making a network client for your task.
* The default version sends a single line
* ("Generic Network Client") to the server,
* reads one line of response, prints it, then exits.
*/

protected void handleConnection(Socket client)
throws IOException {
PrintWriter out = SocketUtil.getWriter(client);
BufferedReader in = SocketUtil.getReader(client);
out.println("Generic Network Client");
System.out.println
("Generic Network Client:n" +
"Made connection to " + host +
" and got ‘" + in.readLine() + "’ in response");
client.close();
}

/** The hostname of the server we’re contacting. */

public String getHost() {
return(host);
}

/** The port connection will be made on. */

public int getPort() {
return(port);
}
}

SocketUtil.java: Provides utilities for wrapping a BufferedReader and PrintWriter around the Socket’s input and output streams, respectively.

import java.net.*;
import java.io.*;

/** A shorthand way to create BufferedReaders and
* PrintWriters associated with a Socket.
*
* Taken from Core Web Programming from
* Prentice Hall and Sun Microsystems Press,
* .
* © 2001 Marty Hall and Larry Brown;
* may be freely used or adapted.
*/

public class SocketUtil {
/** Make a BufferedReader to get incoming data. */

public static BufferedReader getReader(Socket s)
throws IOException {
return(new BufferedReader(
new InputStreamReader(s.getInputStream())));
}

/** Make a PrintWriter to send outgoing data.
* This PrintWriter will automatically flush stream
* when println is called.
*/

public static PrintWriter getWriter(Socket s)
throws IOException {
// Second argument of true means autoflush.
return(new PrintWriter(s.getOutputStream(), true));
}
}

WindowUtilities.java Simplifies the setting of native look and feel.

import javax.swing.*;
import java.awt.*; // For Color and Container classes.

/** A few utilities that simplify using windows in Swing.
*
* Taken from Core Web Programming from
* Prentice Hall and Sun Microsystems Press,
* © 2001 Marty Hall and Larry Brown;
* may be freely used or adapted.
*/

public class WindowUtilities {

/** Tell system to use native look and feel, as in previous
* releases. Metal (Java) LAF is the default otherwise.
*/

public static void setNativeLookAndFeel() {
try {
UIManager.setLookAndFeel(
UIManager.getSystemLookAndFeelClassName());
} catch(Exception e) {
System.out.println("Error setting native LAF: " + e);
}
}

public static void setJavaLookAndFeel() {
try {
UIManager.setLookAndFeel(
UIManager.getCrossPlatformLookAndFeelClassName());
} catch(Exception e) {
System.out.println("Error setting Java LAF: " + e);
}
}

public static void setMotifLookAndFeel() {
try {
UIManager.setLookAndFeel(
"com.sun.java.swing.plaf.motif.MotifLookAndFeel");
} catch(Exception e) {
System.out.println("Error setting Motif LAF: " + e);
}
}

/** A simplified way to see a JPanel or other Container. Pops
* up a JFrame with specified Container as the content pane.
*/

public static JFrame openInJFrame(Container content,
int width,
int height,
String title,
Color bgColor) {
JFrame frame = new JFrame(title);
frame.setBackground(bgColor);
content.setBackground(bgColor);
frame.setSize(width, height);
frame.setContentPane(content);
frame.addWindowListener(new ExitListener());
frame.setVisible(true);
return(frame);
}

/** Uses Color.white as the background color. */

public static JFrame openInJFrame(Container content,
int width,
int height,
String title) {
return(openInJFrame(content, width, height,
title, Color.white));
}

/** Uses Color.white as the background color, and the
* name of the Container’s class as the JFrame title.
*/

public static JFrame openInJFrame(Container content,
int width,
int height) {
return(openInJFrame(content, width, height,
content.getClass().getName(),
Color.white));
}
}

ExitListener.java WindowListener for applications in this chapter.

import java.awt.*;
import java.awt.event.*;

/** A listener that you attach to the top-level JFrame of
* your application, so that quitting the frame exits the
* application.
*
* Taken from Core Web Programming from
* Prentice Hall and Sun Microsystems Press,
* © 2001 Marty Hall and Larry Brown;
* may be freely used or adapted.
*/
public class ExitListener extends WindowAdapter {
public void windowClosing(WindowEvent event) {
System.exit(0);
}
}

Note: Brought from our old site: http://www.salearningschool.com/example_codes/ on Jan 2nd, 2017 From: http://sitestree.com/?p=10234
Categories:Programming Code Examples, Java/J2EE/J2ME, Network Programming
Tags:Java/J2EE/J2MENetwork Programming
Post Data:2017-01-02 16:04:28

Shop Online: https://www.ShopForSoul.com/
(Big Data, Cloud, Security, Machine Learning): Courses: http://Training.SitesTree.com
In Bengali: http://Bangla.SaLearningSchool.com
http://SitesTree.com
8112223 Canada Inc./JustEtc: http://JustEtc.net (Software/Web/Mobile/Big-Data/Machine Learning)
Shop Online: https://www.ShopForSoul.com/
Medium: https://medium.com/@SayedAhmedCanada

UrlTest.java Demonstrates the ease in which the various components of an URL can be determined (host, port, protocol, etc.). #Programming Code Examples #Java/J2EE/J2ME #Network Programming

UrlTest.java  Demonstrates the ease in which the various components of an URL can be determined (host, port, protocol, etc.). 


import java.net.*;

/** Read a URL from the command line, then print
 *  the various components.
 *
 *  Taken from Core Web Programming from
 *  Prentice Hall and Sun Microsystems Press,
 *  .
 *  © 2001 Marty Hall and Larry Brown;
 *  may be freely used or adapted.
 */

public class UrlTest {
  public static void main(String[] args) {
    if (args.length == 1) {
      try {
        URL url = new URL(args[0]);
        System.out.println
          ("URL: " + url.toExternalForm() + "n" +
           "  File:      " + url.getFile() + "n" +
           "  Host:      " + url.getHost() + "n" +
           "  Port:      " + url.getPort() + "n" +
           "  Protocol:  " + url.getProtocol() + "n" +
           "  Reference: " + url.getRef());
      } catch(MalformedURLException mue) {
        System.out.println("Bad URL.");
      }
    } else
      System.out.println("Usage: UrlTest ");
  }
}

Note: Brought from our old site: http://www.salearningschool.com/example_codes/ on Jan 2nd, 2017 From: http://sitestree.com/?p=10233
Categories:Programming Code Examples, Java/J2EE/J2ME, Network Programming
Tags:Java/J2EE/J2MENetwork Programming
Post Data:2017-01-02 16:04:28

Shop Online: https://www.ShopForSoul.com/
(Big Data, Cloud, Security, Machine Learning): Courses: http://Training.SitesTree.com
In Bengali: http://Bangla.SaLearningSchool.com
http://SitesTree.com
8112223 Canada Inc./JustEtc: http://JustEtc.net (Software/Web/Mobile/Big-Data/Machine Learning)
Shop Online: https://www.ShopForSoul.com/
Medium: https://medium.com/@SayedAhmedCanada

UrlRetriever2.java Illustrates how the URL class can simplify communication to an HTTP server. #Programming Code Examples #Java/J2EE/J2ME #Network Programming

UrlRetriever2.java  Illustrates how the URL class can simplify communication to an HTTP server.

import java.net.*;
import java.io.*;

/** Read a remote file using the standard URL class
 *  instead of connecting explicitly to the HTTP server.
 *
 *  Taken from Core Web Programming from
 *  Prentice Hall and Sun Microsystems Press,
 *  .
 *  © 2001 Marty Hall and Larry Brown;
 *  may be freely used or adapted.
 */

public class UrlRetriever2 {
  public static void main(String[] args) {
    checkUsage(args);
    try {
      URL url = new URL(args[0]);
      BufferedReader in = new BufferedReader(
        new InputStreamReader(url.openStream()));
      String line;
      while ((line = in.readLine()) != null) {
        System.out.println("> " + line);
     }
      in.close();
    } catch(MalformedURLException mue) { // URL constructor
        System.out.println(args[0] + "is an invalid URL: " + mue);
    } catch(IOException ioe) { // Stream constructors
      System.out.println("IOException: " + ioe);
    }
  }

  private static void checkUsage(String[] args) {
    if (args.length != 1) {
      System.out.println("Usage: UrlRetriever2 ");
      System.exit(-1);
    }
  }
}




Note: Brought from our old site: http://www.salearningschool.com/example_codes/ on Jan 2nd, 2017 From: http://sitestree.com/?p=10232
Categories:Programming Code Examples, Java/J2EE/J2ME, Network Programming
Tags:Java/J2EE/J2MENetwork Programming
Post Data:2017-01-02 16:04:28

Shop Online: https://www.ShopForSoul.com/
(Big Data, Cloud, Security, Machine Learning): Courses: http://Training.SitesTree.com
In Bengali: http://Bangla.SaLearningSchool.com
http://SitesTree.com
8112223 Canada Inc./JustEtc: http://JustEtc.net (Software/Web/Mobile/Big-Data/Machine Learning)
Shop Online: https://www.ShopForSoul.com/
Medium: https://medium.com/@SayedAhmedCanada

UrlRetriever.java Accepts an URL from the command line, parses the host, port, and URI components from the URL and then retrieves the document. Requires the following classes: #Programming Code Examples #Java/J2EE/J2ME #Network Programming

UrlRetriever.java  Accepts an URL from the command line, parses the host, port, and URI components from the URL and then retrieves the document. Requires the following classes: 


import java.util.*;

/** This parses the input to get a host, port, and file, then
 *  passes these three values to the UriRetriever class to
 *  grab the URL from the Web.
 *
 *  Taken from Core Web Programming from
 *  Prentice Hall and Sun Microsystems Press,
 *  .
 *  © 2001 Marty Hall and Larry Brown;
 *  may be freely used or adapted.
 */

public class UrlRetriever {
  public static void main(String[] args) {
    checkUsage(args);
    StringTokenizer tok = new StringTokenizer(args[0]);
    String protocol = tok.nextToken(":");
    checkProtocol(protocol);
    String host = tok.nextToken(":/");
    String uri;
    int port = 80;
    try {
      uri = tok.nextToken("");
      if (uri.charAt(0) == ':') {
        tok = new StringTokenizer(uri);
        port = Integer.parseInt(tok.nextToken(":/"));
        uri = tok.nextToken("");
      }
    } catch(NoSuchElementException nsee) {
      uri = "/";
    }
    UriRetriever uriClient = new UriRetriever(host, port, uri);
    uriClient.connect();
  }

  /** Warn user if the URL was forgotten. */

  private static void checkUsage(String[] args) {
    if (args.length != 1) {
      System.out.println("Usage: UrlRetriever ");
      System.exit(-1);
    }
  }

  /** Tell user that this can only handle HTTP. */

  private static void checkProtocol(String protocol) {
    if (!protocol.equals("http")) {
      System.out.println("Don't understand protocol " + protocol);
      System.exit(-1);
    }
  }
}




UriRetriever.java  Given a host, port, and URI, retrieves the document from the HTTP server. 

import java.net.*;
import java.io.*;

/** Retrieve a URL given the host, port, and file as three 
 *  separate command-line arguments. A later class 
 *  (UrlRetriever) supports a single URL instead.
 *
 *  Taken from Core Web Programming from 
 *  Prentice Hall and Sun Microsystems Press,
 
 *  © 2001 Marty Hall and Larry Brown;
 *  may be freely used or adapted. 
 */

public class UriRetriever extends NetworkClient {
  private String uri;

  public static void main(String[] args) {
    UriRetriever uriClient
      = new UriRetriever(args[0], Integer.parseInt(args[1]),
                         args[2]);
    uriClient.connect();
  }

  public UriRetriever(String host, int port, String uri) {
    super(host, port); 
    this.uri = uri;
  }

  /** Send one GET line, then read the results one line at a
   *  time, printing each to standard output.
   */

  // It is safe to use blocking IO (readLine), since
  // HTTP servers close connection when done, resulting
  // in a null value for readLine.
  
  protected void handleConnection(Socket uriSocket)
      throws IOException {
    PrintWriter out = SocketUtil.getWriter(uriSocket);
    BufferedReader in = SocketUtil.getReader(uriSocket);
    out.println("GET " + uri + " HTTP/1.0rn");
    String line;
    while ((line = in.readLine()) != null) {
      System.out.println("> " + line);
    }
  }
}





NetworkClient.java

import java.net.*;
import java.io.*;

/** A starting point for network clients. You'll need to
 *  override handleConnection, but in many cases connect can
 *  remain unchanged. It uses SocketUtil to simplify the
 *  creation of the PrintWriter and BufferedReader.
 *
 *  Taken from Core Web Programming from
 *  Prentice Hall and Sun Microsystems Press,
 *  .
 *  © 2001 Marty Hall and Larry Brown;
 *  may be freely used or adapted.
 */

public class NetworkClient {
  protected String host;
  protected int port;

  /** Register host and port. The connection won't
   *  actually be established until you call
   *  connect.
   */

  public NetworkClient(String host, int port) {
    this.host = host;
    this.port = port;
  }

  /** Establishes the connection, then passes the socket
   *  to handleConnection.
   */

  public void connect() {
    try {
      Socket client = new Socket(host, port);
      handleConnection(client);
    } catch(UnknownHostException uhe) {
      System.out.println("Unknown host: " + host);
      uhe.printStackTrace();
    } catch(IOException ioe) {
      System.out.println("IOException: " + ioe);
      ioe.printStackTrace();
    }
  }

  /** This is the method you will override when
   *  making a network client for your task.
   *  The default version sends a single line
   *  ("Generic Network Client") to the server,
   *  reads one line of response, prints it, then exits.
   */

  protected void handleConnection(Socket client)
    throws IOException {
    PrintWriter out = SocketUtil.getWriter(client);
    BufferedReader in = SocketUtil.getReader(client);
    out.println("Generic Network Client");
    System.out.println
      ("Generic Network Client:n" +
       "Made connection to " + host +
       " and got '" + in.readLine() + "' in response");
    client.close();
  }

  /** The hostname of the server we're contacting. */

  public String getHost() {
    return(host);
  }

  /** The port connection will be made on. */

  public int getPort() {
    return(port);
  }
}

SocketUtil.java  Provides utilities for wrapping a BufferedReader  and PrintWriter around the Socket's input and output streams, respectively. 

import java.net.*;
import java.io.*;

/** A shorthand way to create BufferedReaders and
 *  PrintWriters associated with a Socket.
 *
 *  Taken from Core Web Programming from
 *  Prentice Hall and Sun Microsystems Press,
 *  .
 *  © 2001 Marty Hall and Larry Brown;
 *  may be freely used or adapted.
 */

public class SocketUtil {
  /** Make a BufferedReader to get incoming data. */

  public static BufferedReader getReader(Socket s)
      throws IOException {
    return(new BufferedReader(
       new InputStreamReader(s.getInputStream())));
  }

  /** Make a PrintWriter to send outgoing data.
   *  This PrintWriter will automatically flush stream
   *  when println is called.
   */

  public static PrintWriter getWriter(Socket s)
      throws IOException {
    // Second argument of true means autoflush.
    return(new PrintWriter(s.getOutputStream(), true));
  }
}



Note: Brought from our old site: http://www.salearningschool.com/example_codes/ on Jan 2nd, 2017 From: http://sitestree.com/?p=10231
Categories:Programming Code Examples, Java/J2EE/J2ME, Network Programming
Tags:Java/J2EE/J2MENetwork Programming
Post Data:2017-01-02 16:04:28

Shop Online: https://www.ShopForSoul.com/
(Big Data, Cloud, Security, Machine Learning): Courses: http://Training.SitesTree.com
In Bengali: http://Bangla.SaLearningSchool.com
http://SitesTree.com
8112223 Canada Inc./JustEtc: http://JustEtc.net (Software/Web/Mobile/Big-Data/Machine Learning)
Shop Online: https://www.ShopForSoul.com/
Medium: https://medium.com/@SayedAhmedCanada