void send(byte[] data) throws IOException { SocketChannel channel = (SocketChannel) key.channel(); verboseLog("TCP write", data); byte[] lengthArray = new byte[2]; lengthArray[0] = (byte) (data.length >>> 8); lengthArray[1] = (byte) (data.length & 0xFF); ByteBuffer[] buffers = new ByteBuffer[2]; buffers[0] = ByteBuffer.wrap(lengthArray); buffers[1] = ByteBuffer.wrap(data); int nsent = 0; key.interestOps(SelectionKey.OP_WRITE); try { while (nsent < data.length + 2) { if (key.isWritable()) { long n = channel.write(buffers); if (n < 0) throw new EOFException(); nsent += (int) n; if (nsent < data.length + 2 && System.currentTimeMillis() > endTime) throw new SocketTimeoutException(); } else blockUntil(key, endTime); } } finally { if (key.isValid()) key.interestOps(0); } }
public static void createTestFiles() { try { System.out.println("Creating test files ... "); Random rand = new Random(); String rootname = "f-"; long[] sizes = {0, 1, 50000000}; File testdir = new File(dirname); FileUtil.mkdirs(testdir); for (int i = 0; i < sizes.length; i++) { long size = sizes[i]; File file = new File(testdir, rootname + String.valueOf(size)); System.out.println(file.getName() + "..."); FileChannel fc = new RandomAccessFile(file, "rw").getChannel(); long position = 0; while (position < size) { long remaining = size - position; if (remaining > 1024000) remaining = 1024000; byte[] buffer = new byte[new Long(remaining).intValue()]; rand.nextBytes(buffer); ByteBuffer bb = ByteBuffer.wrap(buffer); position += fc.write(bb); } fc.close(); } System.out.println("DONE\n"); } catch (Exception e) { Debug.printStackTrace(e); } }
public static void runTests() { try { // SHA1 sha1Jmule = new SHA1(); MessageDigest sha1Sun = MessageDigest.getInstance("SHA-1"); SHA1 sha1Gudy = new SHA1(); // SHA1Az shaGudyResume = new SHA1Az(); ByteBuffer buffer = ByteBuffer.allocate(1024 * 1024); File dir = new File(dirname); File[] files = dir.listFiles(); for (int i = 0; i < files.length; i++) { FileChannel fc = new RandomAccessFile(files[i], "r").getChannel(); System.out.println("Testing " + files[i].getName() + " ..."); while (fc.position() < fc.size()) { fc.read(buffer); buffer.flip(); byte[] raw = new byte[buffer.limit()]; System.arraycopy(buffer.array(), 0, raw, 0, raw.length); sha1Gudy.update(buffer); sha1Gudy.saveState(); ByteBuffer bb = ByteBuffer.wrap(new byte[56081]); sha1Gudy.digest(bb); sha1Gudy.restoreState(); sha1Sun.update(raw); buffer.clear(); } byte[] sun = sha1Sun.digest(); sha1Sun.reset(); byte[] gudy = sha1Gudy.digest(); sha1Gudy.reset(); if (Arrays.equals(sun, gudy)) { System.out.println(" SHA1-Gudy: OK"); } else { System.out.println(" SHA1-Gudy: FAILED"); } buffer.clear(); fc.close(); System.out.println(); } } catch (Throwable e) { Debug.printStackTrace(e); } }
private void dispatchMessage( TcpAddress incomingAddress, ByteBuffer byteBuffer, long bytesRead) { byteBuffer.flip(); if (logger.isDebugEnabled()) { logger.debug( "Received message from " + incomingAddress + " with length " + bytesRead + ": " + new OctetString(byteBuffer.array(), 0, (int) bytesRead).toHexString()); } ByteBuffer bis; if (isAsyncMsgProcessingSupported()) { byte[] bytes = new byte[(int) bytesRead]; System.arraycopy(byteBuffer.array(), 0, bytes, 0, (int) bytesRead); bis = ByteBuffer.wrap(bytes); } else { bis = ByteBuffer.wrap(byteBuffer.array(), 0, (int) bytesRead); } fireProcessMessage(incomingAddress, bis); }
static void test() throws Exception { ServerSocketChannel ssc = null; SocketChannel sc = null; SocketChannel peer = null; try { ssc = ServerSocketChannel.open().bind(new InetSocketAddress(0)); // loopback connection InetAddress lh = InetAddress.getLocalHost(); sc = SocketChannel.open(new InetSocketAddress(lh, ssc.socket().getLocalPort())); peer = ssc.accept(); // peer sends message so that "sc" will be readable int n = peer.write(ByteBuffer.wrap("Hello".getBytes())); assert n > 0; sc.configureBlocking(false); Selector selector = Selector.open(); SelectionKey key = sc.register(selector, SelectionKey.OP_READ | SelectionKey.OP_WRITE); boolean done = false; int failCount = 0; while (!done) { int nSelected = selector.select(); if (nSelected > 0) { if (nSelected > 1) throw new RuntimeException("More than one channel selected"); Set<SelectionKey> keys = selector.selectedKeys(); Iterator<SelectionKey> iterator = keys.iterator(); while (iterator.hasNext()) { key = iterator.next(); iterator.remove(); if (key.isWritable()) { failCount++; if (failCount > 10) throw new RuntimeException("Test failed"); Thread.sleep(250); } if (key.isReadable()) { done = true; } } } } } finally { if (peer != null) peer.close(); if (sc != null) sc.close(); if (ssc != null) ssc.close(); } }
private void writeMessage(SocketEntry entry, SocketChannel sc) throws IOException { byte[] message = entry.nextMessage(); if (message != null) { ByteBuffer buffer = ByteBuffer.wrap(message); sc.write(buffer); if (logger.isDebugEnabled()) { logger.debug( "Send message with length " + message.length + " to " + entry.getPeerAddress() + ": " + new OctetString(message).toHexString()); } sc.register(selector, SelectionKey.OP_READ); } }
private byte[] _recv(int length) throws IOException { SocketChannel channel = (SocketChannel) key.channel(); int nrecvd = 0; byte[] data = new byte[length]; ByteBuffer buffer = ByteBuffer.wrap(data); key.interestOps(SelectionKey.OP_READ); try { while (nrecvd < length) { if (key.isReadable()) { long n = channel.read(buffer); if (n < 0) throw new EOFException(); nrecvd += (int) n; if (nrecvd < length && System.currentTimeMillis() > endTime) throw new SocketTimeoutException(); } else blockUntil(key, endTime); } } finally { if (key.isValid()) key.interestOps(0); } return data; }
public static void main(String[] argv) { if (argv.length != 3) { usage(); } String tempFile = argv[0]; String testFile = argv[1]; int fileSize = Integer.valueOf(argv[2]).intValue(); int exitcode = 0; int numRead; int numThisBuf; int numWritten; if ((fileSize <= 0) || (fileSize % 4096 != 0)) { System.out.println("Error: size is not a multiple of 4096!!!!!!"); System.out.println(); usage(); } try { int bufSize = 4096; byte[] inBytes = new byte[bufSize]; byte[] outBytes = new byte[bufSize]; Random ioRandom = new Random(2006); ioRandom.nextBytes(outBytes); ByteBuffer inBuf = ByteBuffer.allocate(bufSize); ByteBuffer outBuf = ByteBuffer.wrap(outBytes); // // Loop forever // while (true) { // // Write the temporary file // FileOutputStream fos = new FileOutputStream(tempFile); FileChannel foc = fos.getChannel(); numWritten = 0; while (numWritten < fileSize) { outBuf.clear(); // sets limit to capacity & position to zero while (outBuf.hasRemaining()) { numWritten += foc.write(outBuf); } } // // Move to permanent location // FileChannel srcChannel = new FileInputStream(tempFile).getChannel(); FileChannel dstChannel = new FileOutputStream(testFile).getChannel(); dstChannel.transferFrom(srcChannel, 0, srcChannel.size()); srcChannel.close(); dstChannel.close(); boolean success = (new File(tempFile)).delete(); if (!success) { System.out.println("Warning: unable to delete temporary file"); } // // Read and compare // FileInputStream fis = new FileInputStream(testFile); FileChannel fic = fis.getChannel(); for (numRead = 0, numThisBuf = 0; numRead < fileSize; numThisBuf = 0) { inBuf.rewind(); // Set the buffer position to 0 numThisBuf = fic.read(inBuf); while (numThisBuf < bufSize) { numThisBuf += fic.read(inBuf); } numRead += bufSize; inBuf.rewind(); // Set the buffer position to 0 inBuf.get(inBytes); boolean same = Arrays.equals(inBytes, outBytes); if (same = false) { System.out.println("Data read does not equal data written at " + numRead + " bytes"); } } } } catch (FileNotFoundException fnfe) { fnfe.printStackTrace(System.err); exitcode = 1; // break; } catch (SecurityException se) { se.printStackTrace(System.err); exitcode = 1; // break; } catch (Throwable t) { t.printStackTrace(System.err); exitcode = 1; } System.exit(exitcode); }
private void readMessage(SelectionKey sk, SocketChannel readChannel, TcpAddress incomingAddress) throws IOException { // note that socket has been used SocketEntry entry = (SocketEntry) sockets.get(incomingAddress); if (entry != null) { entry.used(); ByteBuffer readBuffer = entry.getReadBuffer(); if (readBuffer != null) { readChannel.read(readBuffer); if (readBuffer.hasRemaining()) { readChannel.register(selector, SelectionKey.OP_READ, entry); } else { dispatchMessage(incomingAddress, readBuffer, readBuffer.capacity()); } return; } } ByteBuffer byteBuffer = ByteBuffer.wrap(buf); byteBuffer.limit(messageLengthDecoder.getMinHeaderLength()); long bytesRead = readChannel.read(byteBuffer); if (logger.isDebugEnabled()) { logger.debug("Reading header " + bytesRead + " bytes from " + incomingAddress); } MessageLength messageLength = new MessageLength(0, Integer.MIN_VALUE); if (bytesRead == messageLengthDecoder.getMinHeaderLength()) { messageLength = messageLengthDecoder.getMessageLength(ByteBuffer.wrap(buf)); if (logger.isDebugEnabled()) { logger.debug("Message length is " + messageLength); } if ((messageLength.getMessageLength() > getMaxInboundMessageSize()) || (messageLength.getMessageLength() <= 0)) { logger.error( "Received message length " + messageLength + " is greater than inboundBufferSize " + getMaxInboundMessageSize()); synchronized (entry) { entry.getSocket().close(); logger.info("Socket to " + entry.getPeerAddress() + " closed due to an error"); } } else { byteBuffer.limit(messageLength.getMessageLength()); bytesRead += readChannel.read(byteBuffer); if (bytesRead == messageLength.getMessageLength()) { dispatchMessage(incomingAddress, byteBuffer, bytesRead); } else { byte[] message = new byte[byteBuffer.limit()]; byteBuffer.flip(); byteBuffer.get(message, 0, byteBuffer.limit() - byteBuffer.remaining()); entry.setReadBuffer(ByteBuffer.wrap(message)); } readChannel.register(selector, SelectionKey.OP_READ, entry); } } else if (bytesRead < 0) { logger.debug("Socket closed remotely"); sk.cancel(); readChannel.close(); TransportStateEvent e = new TransportStateEvent( DefaultTcpTransportMapping.this, incomingAddress, TransportStateEvent.STATE_DISCONNECTED_REMOTELY, null); fireConnectionStateChanged(e); } }
public void sendDatagram(long sig, byte[] data, int length, String recipAddress, int recipPort) { sendDatagram(sig, ByteBuffer.wrap(data), recipAddress, recipPort); }
public void sendData(long sig, byte[] data) throws IOException { sendData(sig, ByteBuffer.wrap(data)); }