gvsu/cs654/proj1/FileServer.java
josh b86758e2a9 FileServer work
git-svn-id: svn://anubis/gvsu@33 45c1a28c-8058-47b2-ae61-ca45b979098e
2008-03-08 20:29:51 +00:00

97 lines
2.4 KiB
Java

import java.io.*;
import java.net.*;
import java.util.*;
public class FileServer implements Runnable
{
private int m_port;
private String m_rootPath;
private ServerSocket m_serverSocket;
private char m_pathSeparator = '/';
public FileServer(int port, String rootPath)
{
m_port = port;
m_rootPath = rootPath;
if (rootPath.indexOf('\\') >= 0)
m_pathSeparator = '\\';
}
public void run()
{
try {
m_serverSocket = new ServerSocket(m_port);
/* porcess connection requests */
for (;;)
{
Socket clientSocket = m_serverSocket.accept();
Thread thread = new Thread(new FileHandler(clientSocket));
thread.start();
}
} catch (IOException ioe) {
System.out.println("KaZaClient: IO Exception!");
ioe.printStackTrace();
return;
}
}
private class FileHandler implements Runnable
{
private Socket m_socket;
public FileHandler(Socket socket)
{
m_socket = socket;
}
public void run()
{
try {
processRequest();
} catch (Exception e) { }
}
private void processRequest() throws Exception
{
DataOutputStream os = new DataOutputStream(
m_socket.getOutputStream());
BufferedReader br = new BufferedReader(
new InputStreamReader(
m_socket.getInputStream()));
/* read the file name the client is requesting */
String fileName = br.readLine();
String absFileName = m_rootPath + m_pathSeparator + fileName;
FileInputStream fis = null;
try {
fis = new FileInputStream(absFileName);
} catch (Exception e) { }
if (fis != null)
{
sendBytes(fis, os);
}
os.close();
br.close();
m_socket.close();
}
private void sendBytes(FileInputStream fis, OutputStream os)
throws Exception
{
byte[] buff = new byte[1024];
int bytes = 0;
while ((bytes = fis.read(buff)) != -1)
{
os.write(buff, 0, bytes);
}
}
}
}