/*********************************************************************** * Ce programme emet a destination du port argv[1] sur la machine * argv[0], argv[3] messages (datagramme UDP) constitues chacun * de argv[2] caracteres. * * ex: java DgramSend linux03 2005 1000 10 * * L'emission se fait par send sur un DatagramSocket dans le domaine * INET. ***********************************************************************/ package tftp; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.SocketException; import java.net.UnknownHostException; import java.nio.ByteBuffer; import java.nio.channels.DatagramChannel; import java.nio.channels.FileChannel; /* * $Id: TftpClientMain.java 29 2016-06-02 13:29:57Z conan $ */ public class TftpClientMain { public static void main(String[] argv) { DatagramChannel sndChan; ByteBuffer dataBuf[]; InetAddress destAddr; InetSocketAddress rcvAddress; long sent; if (argv.length != 3) { System.out.println("usage: java TftpClientMain "); return; } dataBuf = new ByteBuffer[2]; // we will send 1k byte at a time dataBuf[1] = ByteBuffer.allocate(1024); // calculate size of the Bytebuffer to store the Header // header is composed of : one int to describe the number of bytes necessary for the name // the array of bytes, one long for the starting point and the size of the data (1024) byte [] s2b = argv[2].getBytes(); int headerSize = s2b.length + Long.SIZE/Byte.SIZE + 2*Integer.SIZE/Byte.SIZE; dataBuf[0] = ByteBuffer.allocate(headerSize); try { FileInputStream fin = new FileInputStream(argv[2]); FileChannel fc = fin.getChannel(); // long fileSize = fc.size(); sndChan = DatagramChannel.open(); // on recupere l'adresse IP de la machine cible destAddr = InetAddress.getByName(argv[0]); rcvAddress = new InetSocketAddress(destAddr, Integer.parseInt(argv[1])); sndChan.connect(rcvAddress); int count; long curpos = 0; do { dataBuf[0].clear(); dataBuf[1].clear(); count = fc.read(dataBuf[1]); dataBuf[0].putInt(s2b.length); dataBuf[0].put(s2b); // dataBuf[0].putLong(fileSize); dataBuf[0].putLong(curpos); dataBuf[0].putInt(count); dataBuf[0].flip(); dataBuf[1].flip(); sent = sndChan.write(dataBuf); System.out.println("Sending a datagram of size " + sent); curpos += count; } while (count == 1024); } catch(FileNotFoundException fnf){ fnf.printStackTrace(); return; } catch (SocketException se) { se.printStackTrace(); return; } catch (UnknownHostException ue) { ue.printStackTrace(); return; } catch (IOException ie) { ie.printStackTrace(); return; } } }