// Send File public void sendFile(String chunkName) throws IOException { OutputStream os = null; String currentDir = System.getProperty("user.dir"); chunkName = currentDir + "/src/srcFile/" + chunkName; File myFile = new File(chunkName); byte[] arrby = new byte[(int) myFile.length()]; try { FileInputStream fis = new FileInputStream(myFile); BufferedInputStream bis = new BufferedInputStream(fis); bis.read(arrby, 0, arrby.length); os = csocket.getOutputStream(); System.out.println("Sending File."); os.write(arrby, 0, arrby.length); os.flush(); System.out.println("File Sent."); // os.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { // os.close(); } }
// Doesn't really need to be runnable public void run() { for (; ; ) { try { dispatch(); } catch (IOException x) { x.printStackTrace(); } } }
// send a message to the output stream void sendMessage(String msg) { try { out.writeObject(msg); out.flush(); System.out.println("Send message: " + msg); } catch (IOException ioException) { ioException.printStackTrace(); } }
@Override public void run() { try { out = new ObjectOutputStream(csocket.getOutputStream()); out.flush(); in = new ObjectInputStream(csocket.getInputStream()); // Look for chunks String currentDir = System.getProperty("user.dir"); File folder = new File(currentDir + "/src/srcFile"); File[] listOfFiles = folder.listFiles(); int fileCount = 0; OutputStream os; for (int i = 0; i < listOfFiles.length; i++) { if (listOfFiles[i].isFile() && listOfFiles[i] .getName() .toLowerCase() .contains("chunk")) { // 0 1 10 11 12 13 14 2 20 21 22 23 3 4 5 .... fileCount++; String chunkName = listOfFiles[i].getName().toString(); chunkId = chunkName.substring(chunkName.lastIndexOf('.') + 6); xPayload(chunkId); if ((connTo.equals("2") && Integer.parseInt(chunkId) % noDev == 0) || (connTo.equals("3") && (Integer.parseInt(chunkId) - 1) % noDev == 0) || (connTo.equals("4") && (Integer.parseInt(chunkId) - 2) % noDev == 0) || (connTo.equals("5") && (Integer.parseInt(chunkId) - 3) % noDev == 0) || (connTo.equals("6") && (Integer.parseInt(chunkId) - 4) % noDev == 0)) { System.out.println(chunkName); sendFile(chunkName); } } } xPayload("-1"); System.out.println("All chunks sent."); } catch (IOException ioException) { ioException.printStackTrace(); } finally { // Close connections try { in.close(); out.close(); csocket.close(); System.out.println("Thread closed."); } catch (IOException ioException) { System.out.println("Client " + devId + " disconnected."); } } }
void isAcceptable(SelectionKey k) { ServerSocketChannel ss = (ServerSocketChannel) k.channel(); SocketChannel sn; long b; for (int n = 0; n < 10; n++) { try { sn = ss.accept(); if (sn == null) break; } catch (IOException e) { e.printStackTrace(); k.cancel(); ServerSocketChannel server = Acceptors.remove(k.attachment()); if (server != null) try { server.close(); } catch (IOException ex) { } ; break; } try { sn.configureBlocking(false); } catch (IOException e) { e.printStackTrace(); continue; } b = createBinding(); EventableSocketChannel ec = new EventableSocketChannel(sn, b, mySelector); Connections.put(b, ec); NewConnections.add(b); eventCallback(((Long) k.attachment()).longValue(), EM_CONNECTION_ACCEPTED, null, b); } }
/** * Closes open files and resources associated with the open DDSImage. No other methods may be * called on this object once this is called. */ public void close() { try { if (chan != null) { chan.close(); chan = null; } if (fis != null) { fis.close(); fis = null; } buf = null; } catch (IOException e) { e.printStackTrace(); } }
public void run() { for (; ; ) { try { int n = sel.select(); if (n > 0) processSelectedKeys(); processPendingTargets(); if (shutdown) { sel.close(); return; } } catch (IOException x) { x.printStackTrace(); } } }
public void run() { while (!shutdown) { try { registerTargets(); if (selector.select() > 0) { processSelectedKeys(); } } catch (Exception e) { e.printStackTrace(); } } try { selector.close(); } catch (IOException e) { e.printStackTrace(); } }
public void receiveTarget() { // 接收用户输入的地址,向targets队列中加入任务 try { BufferedReader localReader = new BufferedReader(new InputStreamReader(System.in)); String msg = null; while ((msg = localReader.readLine()) != null) { if (!msg.equals("bye")) { Target target = new Target(msg); addTarget(target); } else { shutdown = true; selector.wakeup(); break; } } } catch (IOException e) { e.printStackTrace(); } }
public void registerTargets() { // 取出targets队列中的任务,向Selector注册连接就绪事件 synchronized (targets) { while (targets.size() > 0) { Target target = (Target) targets.removeFirst(); try { target.channel.register(selector, SelectionKey.OP_CONNECT, target); } catch (IOException x) { try { target.channel.close(); } catch (IOException e) { e.printStackTrace(); } target.failure = x; addFinishedTarget(target); } } } }
/** @param args */ public static void main(String[] args) { FileChannel fc = null; RandomAccessFile raf = null; // StringBuilder sb; if (args.length != 1) { System.out.println("Usage: Ntfs filename"); System.exit(1); } /* sb = new StringBuilder(); int[] foo = {129,4,229,33}; for (int b: foo) { sb.insert(0,String.format("%02X", b)); } System.out.println(sb.toString()); System.exit(0); */ try { raf = new RandomAccessFile(args[0], "r"); fc = raf.getChannel(); Filesystem fs = new Filesystem(fc); fs.demo(); // fs.displayFs(); } catch (FileNotFoundException x) { System.out.println("FNF exp: " + x.getMessage()); } catch (IOException x) { System.out.println("IO exp: " + x.getMessage()); } finally { if (raf != null) try { raf.close(); } catch (IOException e) { e.printStackTrace(); // To change body of catch statement use File | Settings | File // Templates. } } }
// Exchange chunkId, devId, and ownedChunkArray void xPayload(String chunkId) { Socket conn = null; try { // Get message Object[] rPayload = (Object[]) in.readObject(); chunkOwnedClientArray = (String[]) rPayload[1]; connTo = (String) rPayload[0]; chunkOwnedClientList = Arrays.asList(chunkOwnedClientArray); // Send Message Object[] payload = {chunkId, devId, chunkOwnedArray, filename}; out.writeObject(payload); out.flush(); System.out.println("chunkId being sent: " + chunkId + ", connected to: " + connTo); } catch (IOException ioException) { ioException.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } }
void checkIO() { long timeout; if (NewConnections.size() > 0) { timeout = -1; } else if (!Timers.isEmpty()) { long now = new Date().getTime(); long k = Timers.firstKey(); long diff = k - now; if (diff <= 0) timeout = -1; // don't wait, just poll once else timeout = diff; } else { timeout = 0; // wait indefinitely } try { if (timeout == -1) mySelector.selectNow(); else mySelector.select(timeout); } catch (IOException e) { e.printStackTrace(); } }
public void run() { // Here's where everything happens. The select method will // return when any operations registered above have occurred, the // thread has been interrupted, etc. try { while (!stop) { try { if (selector.select() > 0) { if (stop) { break; } // Someone is ready for I/O, get the ready keys Set readyKeys = selector.selectedKeys(); Iterator it = readyKeys.iterator(); // Walk through the ready keys collection and process date requests. while (it.hasNext()) { SelectionKey sk = (SelectionKey) it.next(); it.remove(); SocketChannel readChannel = null; TcpAddress incomingAddress = null; if (sk.isAcceptable()) { // The key indexes into the selector so you // can retrieve the socket that's ready for I/O ServerSocketChannel nextReady = (ServerSocketChannel) sk.channel(); // Accept the date request and send back the date string Socket s = nextReady.accept().socket(); readChannel = s.getChannel(); readChannel.configureBlocking(false); readChannel.register(selector, SelectionKey.OP_READ); incomingAddress = new TcpAddress(s.getInetAddress(), s.getPort()); SocketEntry entry = new SocketEntry(incomingAddress, s); sockets.put(incomingAddress, entry); timeoutSocket(entry); TransportStateEvent e = new TransportStateEvent( DefaultTcpTransportMapping.this, incomingAddress, TransportStateEvent.STATE_CONNECTED, null); fireConnectionStateChanged(e); } else if (sk.isReadable()) { readChannel = (SocketChannel) sk.channel(); incomingAddress = new TcpAddress( readChannel.socket().getInetAddress(), readChannel.socket().getPort()); } else if (sk.isWritable()) { try { SocketEntry entry = (SocketEntry) sk.attachment(); SocketChannel sc = (SocketChannel) sk.channel(); if (entry != null) { writeMessage(entry, sc); } } catch (IOException iox) { if (logger.isDebugEnabled()) { iox.printStackTrace(); } logger.warn(iox); TransportStateEvent e = new TransportStateEvent( DefaultTcpTransportMapping.this, incomingAddress, TransportStateEvent.STATE_DISCONNECTED_REMOTELY, iox); fireConnectionStateChanged(e); sk.cancel(); } } else if (sk.isConnectable()) { try { SocketEntry entry = (SocketEntry) sk.attachment(); SocketChannel sc = (SocketChannel) sk.channel(); if ((!sc.isConnected()) && (sc.finishConnect())) { sc.configureBlocking(false); logger.debug("Connected to " + entry.getPeerAddress()); // make sure conncetion is closed if not used for timeout // micro seconds timeoutSocket(entry); sc.register(selector, SelectionKey.OP_WRITE, entry); } TransportStateEvent e = new TransportStateEvent( DefaultTcpTransportMapping.this, incomingAddress, TransportStateEvent.STATE_CONNECTED, null); fireConnectionStateChanged(e); } catch (IOException iox) { if (logger.isDebugEnabled()) { iox.printStackTrace(); } logger.warn(iox); sk.cancel(); } } if (readChannel != null) { try { readMessage(sk, readChannel, incomingAddress); } catch (IOException iox) { // IO exception -> channel closed remotely if (logger.isDebugEnabled()) { iox.printStackTrace(); } logger.warn(iox); sk.cancel(); readChannel.close(); TransportStateEvent e = new TransportStateEvent( DefaultTcpTransportMapping.this, incomingAddress, TransportStateEvent.STATE_DISCONNECTED_REMOTELY, iox); fireConnectionStateChanged(e); } } } } } catch (NullPointerException npex) { // There seems to happen a NullPointerException within the select() npex.printStackTrace(); logger.warn("NullPointerException within select()?"); } processPending(); } if (ssc != null) { ssc.close(); } } catch (IOException iox) { logger.error(iox); lastError = iox; } if (!stop) { stop = true; synchronized (DefaultTcpTransportMapping.this) { server = null; } } }