1 29 30 import org.apache.commons.logging.Log; 31 import org.apache.commons.logging.LogFactory; 32 33 import jegg.EggBase; 34 import jegg.Port; 35 import jegg.PortException; 36 import transport.AddPacketListenerCommand; 37 import transport.ConfigureLocalAddressCommand; 38 import transport.LocalAddress; 39 import transport.packet.Packet; 40 import transport.packet.PacketTypeEnum; 41 42 43 48 public class PrimeNumberServer extends EggBase 49 { 50 private static final Log LOG = LogFactory.getLog(PrimeNumberServer.class); 51 52 private static final int TCP_PORT = 10100; 53 private Port networkPort; 54 private long nextPrime = 1; 55 56 57 public void handle(Port p) 58 { 59 String name = (String ) p.getId(); 60 61 if (name.endsWith("packet-transport")) 63 { 64 networkPort = p; 65 } 66 } 67 68 public void init() 69 { 70 if (null == networkPort) 71 return; 72 73 int port = Integer.parseInt(getContext().getProperty("tcp-port")); 74 LocalAddress la = new LocalAddress(null,port); 75 try 77 { 78 networkPort.send(getContext().createMessage(new ConfigureLocalAddressCommand(la))); 79 networkPort.send(getContext().createMessage(new AddPacketListenerCommand(null,getContext().getPort()))); 81 } 82 catch (PortException e) 83 { 84 LOG.error("Failed to configure network address: ", e); 85 } 86 } 87 88 91 public void handle(Object message) 92 { 93 LOG.warn("Unexpected message: " + message); 94 } 95 96 public void handle(Packet p) 97 { 98 Packet response = new Packet(PacketTypeEnum.APPLICATION,new Long (getNextPrime())); 101 response.setChannelID(p.getChannelID()); 102 try 103 { 104 networkPort.send(getContext().createMessage(response)); 105 } 106 catch (PortException e) 107 { 108 LOG.error("Unable to send response packet: ", e); 109 } 110 } 111 112 private long getNextPrime() 113 { 114 for(;;) 115 { 116 nextPrime += 2; 117 boolean notPrime = false; 118 for (long el=2; el < nextPrime/2; ++el) 119 { 120 if (0 == nextPrime%el) 121 { 122 notPrime = true; 123 break; 124 } 125 } 126 if (!notPrime) return nextPrime; 127 } 128 } 129 } 130 | Popular Tags |