package jp.gr.javacons.industry.seminar.sockettempmonitor; import java.util.Vector; import java.net.*; import java.io.*; import jp.gr.javacons.industry.seminar.tempmonitor.DataCollector; public class DataCollectorStub implements Runnable { private DataCollector collector; private ServerSocket serverSocket; private Thread acceptWaitThread; private static int port; public DataCollectorStub(DataCollector collector, int port){ this.collector = collector; this.port = port; try{ serverSocket = new ServerSocket(port); }catch(IOException ex){ ex.printStackTrace(); System.exit(1); } acceptWaitThread = new Thread(this); acceptWaitThread.start(); } public DataCollectorStub(DataCollector collector){ this(collector, 9000); } public void stop(){ acceptWaitThread = null; } public void run(){ Thread currentThread = Thread.currentThread(); while(currentThread == acceptWaitThread){ try{ Socket clientSocket = serverSocket.accept(); (new Connection(clientSocket)).start(); }catch(IOException ex){ ex.printStackTrace(); }catch(SecurityException ex){ ex.printStackTrace(); } } } public void getChannelSize(DataOutputStream outputStream) throws IOException { outputStream.writeInt(collector.getChannelSize()); outputStream.flush(); } public void getMinimumValue(DataOutputStream outputStream) throws IOException { outputStream.writeInt(collector.getMinimumValue()); outputStream.flush(); } public void getMaximumValue(DataOutputStream outputStream) throws IOException { outputStream.writeInt(collector.getMaximumValue()); outputStream.flush(); } public void getData(DataOutputStream outputStream) throws IOException { Vector data = collector.getData(); outputStream.writeInt(data.size()); for(int i = 0 ; i < data.size() ; i++){ outputStream.writeDouble(((Double)data.elementAt(i)).doubleValue()); } outputStream.flush(); } public class Connection implements Runnable { protected DataInputStream inputStream; protected DataOutputStream outputStream; protected Socket socket; protected Thread thread; public Connection(Socket socket) throws IOException { this.socket = socket; } public void start(){ thread = new Thread(this); thread.start(); } public void stop(){ thread = null; } public void run(){ try{ OutputStream ostream = outputStream = new DataOutputStream( new BufferedOutputStream( socket.getOutputStream())); InputStream istream = inputStream = new DataInputStream( new BufferedInputStream( socket.getInputStream())); }catch(IOException ex){ stop(); } Thread currentThread = Thread.currentThread(); while(currentThread == thread){ try{ String methodName = (String)inputStream.readUTF(); if(methodName.equals("getChannelSize")){ getChannelSize(outputStream); }else if(methodName.equals("getMinimumValue")){ getMinimumValue(outputStream); }else if(methodName.equals("getMaximumValue")){ getMaximumValue(outputStream); }else if(methodName.equals("getData")){ getData(outputStream); } }catch(IOException ex){ stop(); } } } } }