/* Author: Maer Melo
* Email: salalbr@gmail.com
* Date: 12-7-2011
*/
package cs.mm.network;
import cs.mm.file.FileRead;
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
public class Server implements Runnable {
private int listPort;
public Server(int listPort) {
this.listPort = listPort;
}
public void run() {
try {
ServerSocket serverSocket = new ServerSocket(listPort);
while (true) {
Socket client = serverSocket.accept();
Thread clientThread = new Thread(new ClientConnection(client));
clientThread.start();
}
}
catch (Exception e) {
System.out.println("Fatal Error on server socket: " + e);
}
}
class ClientConnection implements Runnable {
private Socket client;
private Scanner inScanner;
private PrintStream outPrintStream;
private Boolean interrupt;
long fileSize;
String fileName;
public ClientConnection(Socket client) {
this.client = client;
this.interrupt = false;
}
public void run() {
try {
this.inScanner = new Scanner(client.getInputStream());
this.outPrintStream = new PrintStream(client.getOutputStream());
performHandshake();
getFileDetails();
FileRead writeIntoFS = new FileRead(client, fileName, fileSize);
writeIntoFS.writeToDisk();
}
catch (Exception e) {
System.out.println("Error during client connection:" + new Object[] { e } );
}
}
private void performHandshake() throws InterruptedException, IOException {
isInterrupted();
System.out.println("Sending message HELLO.");
this.outPrintStream.println("HELLO");
String ack = this.inScanner.nextLine();
if(ack.equals("HITHERE")) {
System.out.println("Received message HITHERE.");
}
else {
throw new IOException(String.format("Error during acknowledgement: %s\n", new Object[] { ack } ));
}
}
private void getFileDetails() throws InterruptedException, IOException {
isInterrupted();
this.fileName = this.inScanner.nextLine();
this.fileSize = Integer.parseInt(this.inScanner.nextLine());
this.outPrintStream.println("FILEOK");
}
private void isInterrupted() throws InterruptedException {
if(this.interrupt)
throw new InterruptedException("Thread interrupted.");
}
}
}
~