PageRenderTime 21ms CodeModel.GetById 8ms app.highlight 10ms RepoModel.GetById 1ms app.codeStats 0ms

/examples/kilim/examples/Ping.java

http://github.com/kilim/kilim
Java | 147 lines | 110 code | 13 blank | 24 comment | 17 complexity | 33df531e6a463ea8c0712073e5891873 MD5 | raw file
  1/* Copyright (c) 2006, Sriram Srinivasan
  2 *
  3 * You may distribute this software under the terms of the license 
  4 * specified in the file "License"
  5 */
  6
  7package kilim.examples;
  8
  9import java.io.EOFException;
 10import java.io.IOException;
 11import java.net.InetSocketAddress;
 12import java.nio.ByteBuffer;
 13import java.nio.channels.SocketChannel;
 14
 15import kilim.Pausable;
 16import kilim.Scheduler;
 17import kilim.nio.EndPoint;
 18import kilim.nio.NioSelectorScheduler;
 19import kilim.nio.SessionTask;
 20
 21/**
 22 * Example showing kilim's support for NIO.
 23 * Usage: java kilim.examples.Ping -server in one window
 24 *    and java kilim.examples.Ping -client in one or more windows.
 25 * The client sends a number of 100 byte packets which are then echoed by the server. 
 26 */
 27
 28public class Ping {
 29    static int PACKET_LEN = 100;
 30    static boolean server = false;
 31    static int port = 7262;
 32    
 33    public static void main(String args[]) throws Exception {
 34        if (args.length == 0) {
 35            usage();
 36        } else if (args[0].equalsIgnoreCase("-server")) {
 37            server = true;
 38        } else if (args[0].equalsIgnoreCase("-client")) {
 39            server = false;
 40        } else {
 41            usage();
 42        }
 43        if (args.length > 1)
 44            parsePort(args[1]);
 45        System.out.println("kilim.examples.Ping " + (server ? "-server " : "-client ") + port);
 46        if (server) {
 47            Server.run();
 48        } else {
 49            Client.run();
 50        }
 51    }
 52    /**
 53     * Server is a SessionTask, which means an instance of it is created by the 
 54     * NioSelectorScheduler on an incoming connection. 
 55     * The task contains an endpoint object, the bridge between the NIO system 
 56     * and Kilim's scheduling. 
 57     */
 58    public static class Server extends SessionTask {
 59        public static void run() throws IOException {
 60            Scheduler sessionScheduler = Scheduler.getDefaultScheduler(); // The scheduler/thread pool on which all tasks will be run
 61            NioSelectorScheduler nio = new NioSelectorScheduler(); // Starts a single thread that manages the select loop
 62            nio.listen(port, Server.class, sessionScheduler); // 
 63        }
 64        
 65        @Override
 66        public void execute() throws Pausable, Exception {
 67            System.out.println("[" + this.id + "] Connection rcvd"); 
 68            try {
 69                while (true) {
 70                    EndPoint ep = getEndPoint();
 71                    ByteBuffer buf = ByteBuffer.allocate(PACKET_LEN);
 72                    buf = ep.fill(buf, PACKET_LEN); // Pauses until at least PACKET_LEN bytes have been rcvd in buf.
 73                    System.out.println("[" + this.id + "] Received pkt"); 
 74                    buf.flip();
 75                    ep.write(buf);
 76                    System.out.println("[" + this.id + "] Echoed pkt"); 
 77                }
 78            } catch (EOFException eofe) {
 79                System.out.println("[" + this.id + "] Connection terminated"); 
 80            } catch (IOException ioe) {
 81                System.out.println("[" + this.id + "] IO Exception: " + ioe.getMessage()); 
 82            }
 83        }
 84    }
 85    
 86    /**
 87     * The Client is a conventional Java socket application. 
 88     */
 89    public static class Client {
 90        public static void run() throws IOException {
 91            SocketChannel ch = SocketChannel.open(new InetSocketAddress("localhost", port));
 92
 93            // Init ping packet 
 94            ByteBuffer bb = ByteBuffer.allocate(PACKET_LEN);
 95            for (int i = 0; i < PACKET_LEN; i++) {
 96                bb.put((byte)i);
 97            }
 98            bb.flip();
 99            
100            // Ping 5 times        
101            for (int i = 0 ; i < 5; i++) {
102                System.out.print("Ping");
103                writePkt(ch, bb);
104                System.out.println(" .. ");
105                // Read echo
106                readPkt(ch, bb);
107                bb.flip();
108                System.out.println("        reply rcvd");
109            }
110        }
111
112        private static void readPkt(SocketChannel ch, ByteBuffer bb) throws IOException, EOFException {
113            int remaining = PACKET_LEN;
114            bb.clear();
115            while (remaining > 0) {
116                int n = ch.read(bb);
117                if (n == -1) {
118                    ch.close();
119                    throw new EOFException();
120                }
121                remaining -= n;
122            }
123        }
124
125        private static void writePkt(SocketChannel ch, ByteBuffer bb) throws IOException {
126            // Write packet
127            int remaining = PACKET_LEN;
128            while (remaining > 0) {
129                int n = ch.write(bb);
130                remaining -= n;
131            }
132        }
133    }
134    static private void usage() {
135        System.err.println("Run java kilim.examples.Ping -server [port] in one window");
136        System.err.println("and      kilim.examples.Ping -client [port] in one or more");
137        System.exit(1);
138    }
139    
140    static void parsePort(String portstr) {
141        try {
142            port = Integer.parseInt(portstr);
143        } catch (Exception e) {
144            usage();
145        }
146    }
147}