added client support for download a file

git-svn-id: svn://anubis/gvsu@51 45c1a28c-8058-47b2-ae61-ca45b979098e
This commit is contained in:
josh 2008-03-09 01:47:14 +00:00
parent 0d5e54627a
commit 15f81fc270

View File

@ -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<ClientDownloader> 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<ClientDownloader>();
}
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);
}
}
}
}