Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import org.apache.commons.io.input.ReversedLinesFileReader;
- import java.net.*;
- import java.io.*;
- public class FixedMessageSequenceServer {
- public static String possiblyEmpty = returnLastNumber();
- public static int newPosition = Integer.parseInt( possiblyEmpty );
- public static void main(String[] args) throws IOException , InterruptedException {
- ServerSocket serverSocket = null;
- try {
- serverSocket = new ServerSocket(4444);
- } catch (IOException e) {
- System.err.println("Could not listen on port: 4444.");
- System.exit(1);
- }
- Socket clientSocket = null;
- try {
- clientSocket = serverSocket.accept();
- } catch (IOException e) {
- System.err.println("Accept failed.");
- System.exit(1);
- }
- PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
- BufferedReader in = new BufferedReader(
- new InputStreamReader(
- clientSocket.getInputStream()));
- String inputLine, outputLine;
- String lastLineFromLogFileString = returnLastNumber();
- int lastLineFromLogFile = Integer.parseInt(returnLastNumber());
- lastLineFromLogFile += 1; ///we want to start at the Next State, hence +1
- FixedMessageSequenceProtocol fmsp = new FixedMessageSequenceProtocol(lastLineFromLogFile );
- outputLine = fmsp.processInput(null ); // passing null means we start with state=waiting and it should send "Give me prmission to send state"
- out.println(outputLine);
- try {
- while ((inputLine = in.readLine()) != null) {
- System.out.println(inputLine); // it starts off with "Permission granted."
- if (inputLine.equals("y")){
- out.println("inputOfYes");
- newPosition++;
- boolean boolLog = false;
- boolLog = logPosition();
- if (boolLog){
- out.println("nowlogged");
- }
- else { System.out.print("not logged");
- }
- }//end-IF
- outputLine = fmsp.processInput(inputLine);
- try { //Sleep to prevent synchronization issues ??
- Thread.sleep( 10 );
- out.println(outputLine);
- }
- catch (InterruptedException ie) {}
- if (outputLine.equals("Bye."))
- break;
- }
- } catch(SocketException so) { } /*END LARGE TRY-CATCH*/
- out.close();
- in.close();
- clientSocket.close();
- serverSocket.close();
- }
- public static boolean logPosition(){
- try {
- File file = new File("C:\\\\Java_Scratch3_new_cleaned_Mar12\\\\FixedMessageLog.txt");
- PrintStream ps = null;
- ps = new PrintStream( new FileOutputStream(file, true) );
- ps.println(newPosition);
- }
- catch(FileNotFoundException fe){
- }
- return true;
- }
- public static String returnLastNumber() {
- String lastLine = null;
- try {
- File someFile = new File("C:\\\\Java_Scratch3_new_cleaned_Mar12\\\\FixedMessageLog.txt");
- ReversedLinesFileReader reader = new ReversedLinesFileReader( someFile );
- lastLine = reader.readLine();
- if (lastLine == null){
- lastLine = "0";
- }
- } catch ( IOException ee) {
- }
- return lastLine;
- }
- }// end class FixedMessageSequenceServer
Add Comment
Please, Sign In to add comment