In this tutorial, I will just add one more implementation on the ServerListener class. This is the continuation from the previous thread, where I was able to read and write ASCII file from the Web Server to the Web Browser.
Introduction to Web Server Application PHP Code:
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.StringTokenizer;
public class ServerListener extends Thread {
private Socket sock;
public ServerListener(Socket sock) {
this.sock = sock;
}
private static void sendBytes(FileInputStream fis, OutputStream os) throws Exception {
// Construct a 1K buffer to hold bytes on their way to the socket.
byte[] buffer = new byte[1024];
int bytes = 0;
// Copy requested file into the socket's output stream.
while((bytes = fis.read(buffer)) != -1 )
os.write(buffer, 0, bytes);
}
public void run() {
try {
BufferedReader br = new BufferedReader(new InputStreamReader(sock.getInputStream()));
String line = br.readLine();
StringTokenizer st = new StringTokenizer(line, " ");
String file = st.nextToken();
file = st.nextToken();
file = file.replaceAll("/", "");
// DETERMINE THE TYPE
StringTokenizer st2 = new StringTokenizer(file, ".");
String fType = st2.nextToken();
fType = st2.nextToken();
if (fType.equals("html") || fType.equals("txt")) {
BufferedReader fr = new BufferedReader(new FileReader(file));
String fileLine = fr.readLine();
PrintWriter pw = new PrintWriter(sock.getOutputStream());
while (fileLine != null) {
pw.println(fileLine);
pw.flush();
fileLine = fr.readLine();
}
br.close();
fr.close();
pw.close();
} else {
FileInputStream fis = new FileInputStream(file);
sendBytes(fis, sock.getOutputStream());
}
} catch (IOException ioe) {
System.out.println("IOException: " + ioe.getMessage());
} catch (Exception e) {
System.out.println("Exception: " + e.getMessage());
}
}
}
Hopefully some comment on the code is self explanatory. Feel free to ask questions and add some more implementation which you think is more effective than what I have, but the most important one in this new implementation is the sendByte() method implementation:
PHP Code:
private static void sendBytes(FileInputStream fis, OutputStream os) throws Exception {
// Construct a 1K buffer to hold bytes on their way to the socket.
byte[] buffer = new byte[1024];
int bytes = 0;
// Copy requested file into the socket's output stream.
while((bytes = fis.read(buffer)) != -1 )
os.write(buffer, 0, bytes);
}
This is the method which enables our Web Server to be able to send back response by bytes back to the client's requests.
STILL FOR MY CLASSMATES, DON'T JUST COPY AND PASTE