diff --git a/cs654/proj1/KaZaClient.java b/cs654/proj1/KaZaClient.java index f529dbb..e1f9ebc 100644 --- a/cs654/proj1/KaZaClient.java +++ b/cs654/proj1/KaZaClient.java @@ -6,12 +6,14 @@ import java.util.*; public class KaZaClient { public static final int LISTEN_PORT = 3443; + private static int m_transferIndex = 0; private String m_sharedFolder; private boolean m_connected = false; private Socket m_socket; private DataOutputStream m_os; private FileServer m_fileServer; + private Vector m_clientDownloaders; public KaZaClient(String userName, int kbps, String sharedFolder, String server) @@ -51,6 +53,7 @@ public class KaZaClient m_fileServer = new FileServer(LISTEN_PORT, m_sharedFolder); Thread fsThread = new Thread(m_fileServer); m_connected = true; + m_clientDownloaders = new Vector(); } public boolean connected() { return m_connected; } @@ -124,4 +127,74 @@ public class KaZaClient String fileName = ""; String fileDescription = ""; } + + public void downloadFile(String host, String fileName) + { + ClientDownloader cd = new ClientDownloader(host, fileName); + synchronized (m_clientDownloaders) + { + m_clientDownloaders.add(cd); + } + Thread t = new Thread(cd); + t.start(); + } + + public synchronized int getTransferIndex() + { + return m_transferIndex++; + } + + public class ClientDownloader implements Runnable + { + private String m_host; + private String m_fileName; + private int m_index; + + public ClientDownloader(String host, String fileName) + { + m_host = host; + m_fileName = fileName; + m_index = getTransferIndex(); + } + + public void run() + { + FileOutputStream fos; + try { + fos = new FileOutputStream(m_fileName); + } catch (Exception e) { + return; + } + + try + { + Socket socket = new Socket(m_host, LISTEN_PORT); + DataOutputStream os = new DataOutputStream(socket.getOutputStream()); + DataInputStream is = new DataInputStream(socket.getInputStream()); + + os.writeBytes(m_fileName + "\n"); + + byte[] buff = new byte[1500]; + + while (!socket.isClosed()) + { + int bytesRead = is.read(buff, 0, buff.length); + if (bytesRead < 0) + break; + fos.write(buff, 0, bytesRead); + } + } + catch (Exception e) { } + + try { + fos.close(); + } catch (Exception e) { + } + + synchronized (m_clientDownloaders) + { + m_clientDownloaders.remove(this); + } + } + } }