TradingClient.java
资源名称:某公司的java培训教材 [点击查看]
上传用户:dinglihq
上传日期:2013-02-04
资源大小:99958k
文件大小:3k
源码类别:
Java编程
开发平台:
Java
- package bible.rmi.example4;
- import java.util.*;
- import javax.naming.*;
- import weblogic.rmi.*;
- /**
- * Periodically enters orders to the remote server and remotely
- * receive updates of executions.
- */
- public class TradingClient extends TimerTask
- implements Runnable, ExecutionAlert {
- /** orderNumber */
- private static int orderNumber = 0;
- /**
- * Method notifyOfExecution
- *
- *
- * @param exec
- *
- */
- public void notifyOfExecution(Execution exec) throws java.rmi.RemoteException{
- System.out.println("An order has been executed!");
- System.out.println("Time: " + new Date());
- System.out.println(exec + "n");
- }
- /**
- * Places a stock order with the remote server.
- */
- public void run() {
- System.out.println("Client now placing an order... ");
- System.out.println(" Time: " + new Date() + "n");
- InitialContext ctx = null;
- try {
- // Get the remote stub for the Price server via JNDI.
- ctx = Environment.getInitialContext();
- PriceServer server =
- (PriceServer) ctx.lookup(PriceServer.PRICESERVERNAME);
- // Get the list of securities managed by the server.
- String securities [] = server.getSecurities();
- // Create a new Order instance
- Order order = new Order();
- Random rand = new Random();
- // Increment the order number
- order.setNumber(++orderNumber);
- // Choose one of the available securities at random
- order.setSymbol(securities [rand.nextInt(securities.length)]);
- // Choose a random number of shares
- order.setShares(100 * (rand.nextInt(9) + 1));
- // Enter the order via a remote call to the server.
- // Pass the reference to ourselves so the server can call back.
- server.enterMarketOrder(order, this);
- } catch (Exception e) {
- e.printStackTrace();
- } finally {
- try {
- ctx.close();
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- }
- /**
- * Instantiates a client and puts it on a repeating timer.
- * @param args
- */
- public static void main(String[] args) {
- try {
- Timer t = new Timer();
- TradingClient client = new TradingClient();
- Context ctx = Environment.getInitialContext();
- ctx.bind("TradingClient", client);
- System.out
- .println("TradingClient was started and bound in the registry "
- + "to the name TradingClient");
- t.schedule(client, 5000, 45000);
- } catch (Exception e) {
- e.printStackTrace();
- System.exit(1);
- }
- }
- }