diff --git a/src/main/java/ru/molokoin/App.java b/src/main/java/ru/molokoin/App.java index 3ada3e9..bb7a7ec 100644 --- a/src/main/java/ru/molokoin/App.java +++ b/src/main/java/ru/molokoin/App.java @@ -9,7 +9,7 @@ import javafx.stage.Stage; /** - * JavaFX App + * */ public class App extends Application { diff --git a/src/main/java/ru/molokoin/ExchangeServer.java b/src/main/java/ru/molokoin/ExchangeServer.java index 64d33a5..fdaa8ec 100644 --- a/src/main/java/ru/molokoin/ExchangeServer.java +++ b/src/main/java/ru/molokoin/ExchangeServer.java @@ -16,15 +16,17 @@ public class ExchangeServer extends Thread{ private int port = 8081; private int num = 0; public static boolean isActive; - public ServerSocket serverSocket; - public Socket socket; + public static ServerSocket serverSocket; + public static Socket socket; - ExchangeServer(){ + ExchangeServer() throws Exception{ isActive = true; + serverSocket = new ServerSocket(port); } - ExchangeServer (int port){ + ExchangeServer (int port) throws Exception{ isActive = true; setPort(port); + serverSocket = new ServerSocket(port); } /** * @return the port @@ -39,85 +41,98 @@ public class ExchangeServer extends Thread{ this.port = port; } //осановка сервера - public void finish(){ + public void finish() throws Exception{ isActive = false; } + public void connect() throws Exception{} + //запуск сервера @Override public void run(){ System.out.printf("%s started... \n", Thread.currentThread().getName()); - try (ServerSocket serverSocket = new ServerSocket(port)) { + try { System.out.println("Server started at port: " + port + " ..."); + do { + if (isActive){ + // ожидаем подключения + Socket socket = serverSocket.accept(); + System.out.println("Client connected ..."); + num++; - while (isActive) { - // ожидаем подключения - Socket socket = serverSocket.accept(); - System.out.println("Client connected ..."); - num++; - - // для подключившегося клиента открываем потоки - // чтения и записи - try (BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream(), StandardCharsets.UTF_8)); - PrintWriter output = new PrintWriter(socket.getOutputStream())) { + // для подключившегося клиента открываем потоки + // чтения и записи + try (BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream(), StandardCharsets.UTF_8)); + PrintWriter output = new PrintWriter(socket.getOutputStream())) { - // ждем первой строки запроса - while (!input.ready()) ; + // ждем первой строки запроса + while (!input.ready()); - // считываем и печатаем все что было отправлено клиентом - System.out.println(); - String firstLine = null; - String querry = null; - while (input.ready()) { - String line = input.readLine(); - if (firstLine == null){ - firstLine = line; - if(firstLine.startsWith("GET")){ - querry = "GET"; - } - if(firstLine.startsWith("POST")){ - querry = "POST"; + // считываем и печатаем все что было отправлено клиентом + System.out.println(); + String firstLine = null; + String querry = null; + while (input.ready()) { + String line = input.readLine(); + if (firstLine == null){ + firstLine = line; + if(firstLine.startsWith("GET")){ + querry = "GET"; + } + if(firstLine.startsWith("POST")){ + querry = "POST"; + } + System.out.println("firstLine: " + firstLine); + System.out.println("querry: " + querry); } - System.out.println("firstLine: " + firstLine); - System.out.println("querry: " + querry); + //System.out.println(line); } - //System.out.println(line); - } - // отправляем ответ - System.out.println("отправка ответа от сервера:"); - String path = new File("").getAbsolutePath(); - String fileName = "upload.http"; - path = path + "/src/main/webapp/"; - File file = new File(path + fileName); - //String text = ""; - try (BufferedReader br = new BufferedReader(new FileReader(file))){ - String line; - while ((line = br.readLine()) != null) { - System.out.println(line); - output.println(line); - //text = text + " " + line; + // отправляем ответ + System.out.println("отправка ответа от сервера:"); + String path = new File("").getAbsolutePath(); + String fileName = "upload.http"; + path = path + "/src/main/webapp/"; + File file = new File(path + fileName); + //String text = ""; + try (BufferedReader br = new BufferedReader(new FileReader(file))){ + String line; + while ((line = br.readLine()) != null) { + System.out.println(line); + output.println(line); + //text = text + " " + line; + } + output.flush(); + } + catch (IOException e) { + e.printStackTrace(); } - output.flush(); - } - catch (IOException e) { - e.printStackTrace(); - } - // по окончанию выполнения блока try-with-resources потоки, - // а вместе с ними и соединение будут закрыты - System.out.println("Client disconnected!"); - System.out.println("num: " + num); + // по окончанию выполнения блока try-with-resources потоки, + // а вместе с ними и соединение будут закрыты + System.out.println("Client disconnected!"); + System.out.println("num: " + num); + } } - } - System.out.printf("%s finished... \n", Thread.currentThread().getName()); + else { + System.out.printf("%s finished... \n", Thread.currentThread().getName()); + serverSocket.close(); + socket.close(); + return; //завершение потока + } + } while (true); + //serverSocket.close(); } catch (IOException ex) { ex.printStackTrace(); } } public static void main(String[] args) { - new ExchangeServer().start(); + try { + new ExchangeServer().start(); + } catch (Exception e) { + System.out.println(e); + } } } diff --git a/src/main/java/ru/molokoin/MainFrameController.java b/src/main/java/ru/molokoin/MainFrameController.java index 67a5a8e..fc5573d 100644 --- a/src/main/java/ru/molokoin/MainFrameController.java +++ b/src/main/java/ru/molokoin/MainFrameController.java @@ -19,7 +19,11 @@ public class MainFrameController implements Initializable{ @Override public void initialize(URL location, ResourceBundle resources) { System.out.println("Инициализация компонентов интерфейса ..."); - server = new ExchangeServer(); + try { + server = new ExchangeServer(); + } catch (Exception ex) { + System.out.println(ex); + } } @FXML @@ -28,10 +32,15 @@ public class MainFrameController implements Initializable{ btn.setText("STOP"); server.start(); - }else { - btn.setText("START"); + + }else { + btn.setText("START"); + try { server.finish(); + } catch (Exception ex) { + System.out.println(ex); } + } } } diff --git a/src/main/java/ru/molokoin/SystemInfo.java b/src/main/java/ru/molokoin/SystemInfo.java deleted file mode 100644 index 9def5ed..0000000 --- a/src/main/java/ru/molokoin/SystemInfo.java +++ /dev/null @@ -1,13 +0,0 @@ -package ru.molokoin; - -public class SystemInfo { - - public static String javaVersion() { - return System.getProperty("java.version"); - } - - public static String javafxVersion() { - return System.getProperty("javafx.version"); - } - -} \ No newline at end of file diff --git a/src/main/java/ru/molokoin/UploadServer.java b/src/main/java/ru/molokoin/UploadServer.java deleted file mode 100644 index 368d7e7..0000000 --- a/src/main/java/ru/molokoin/UploadServer.java +++ /dev/null @@ -1,220 +0,0 @@ -package ru.molokoin; - -/** - UploadServer program - simple file upload web-server - Author: Denis Volkov (c) 2007 - For information and support visit http://www.denvo.ru - - This program is FREEWARE, you are free to use any part of code - as well as whole program in your development provided that you - remain original copyrights and site name in your source. - - The product is distributed "as is". The author of the Product will - not be liable for any consequences, loss of profit or any other kind - of loss, that may occur while using the product itself and/or together - with any other software. - -*/ - -import java.net.*; -import java.io.*; -import java.security.*; -import java.util.*; -import java.util.regex.*; -import java.nio.charset.*; - -public class UploadServer extends Thread -{ - private final static String httpHeader = "HTTP/1.1 200 OK\r\n" - + "Content-Type: text/html\r\n" - + "\r\n"; - private final static String uploadFormString = httpHeader - + "
\r\n" - + "\r\n" - + "\r\n" - + "
\r\n\r\n"; - - private final Charset streamCharset = Charset.forName("ISO-8859-1"); - - private ServerSocket serverSocket; - private Socket clientSocket; - - UploadServer(int port) throws Exception - { - serverSocket = new ServerSocket(port); - System.err.println("Server ready @" + port); - } - - public void run() - { - while(true) - { - try - { - clientSocket = serverSocket.accept(); - System.err.println("Client connection accepted from " - + clientSocket.getInetAddress().toString()); - // Read and process data from socket - processConnection(); - } - catch(Exception e) - { - System.err.println("Exception in run's main loop"); - e.printStackTrace(); - } - // Close socket - try - { - clientSocket.close(); - } - catch(Exception e) { } - System.err.println("Client connection closed"); - } - } - - private void processConnection() throws Exception - { - InputStream inStream = clientSocket.getInputStream(); - BufferedReader in = new BufferedReader(new InputStreamReader(inStream, streamCharset)); - OutputStream out = clientSocket.getOutputStream(); - // Read requiest header - String headerLine, firstLine = null; - Map headerData = new TreeMap(); - Pattern headerPattern = Pattern.compile("([^\\:]+)\\:(.*)"); - while((headerLine = in.readLine()).length() > 0) - { - if(firstLine == null) - firstLine = headerLine; - else - { - Matcher m = headerPattern.matcher(headerLine); - if(m.matches()) - { - headerData.put(m.group(1).trim(), m.group(2).trim()); - } - } - System.out.println("HEADER: " + headerLine); - } - // Process first line of request - if(firstLine.startsWith("GET")) - { - System.out.println("Send upload form"); - // Show upload form - out.write(uploadFormString.getBytes()); - } - else if(firstLine.startsWith("POST")) - { - // Get body info - int contentLength = Integer.parseInt((String)(headerData.get("Content-Length"))); - String contentType = (String)(headerData.get("Content-Type")); - String boundary = "\r\n--" + contentType.substring(contentType.indexOf("boundary=") + 9) + "--"; - System.out.println("File upload, reading body: " + contentLength + " bytes"); - // Prepare to reading - Pattern fileNamePattern = Pattern.compile("filename=\"([^\"]+)\""); - OutputStreamWriter writer = null; - MessageDigest digestMD5 = MessageDigest.getInstance("MD5"); - String fileName = null; - String prevBuffer = ""; - char[] buffer = new char[16 << 10]; - int totalLength = contentLength; - // Reading loop - while(contentLength > 0) - { - if(writer == null) - { - // Read strings - String bodyLine = in.readLine(); - contentLength -= bodyLine.length() + 2; - // Find name of file - if(bodyLine.length() > 0) - { - Matcher m = fileNamePattern.matcher(bodyLine); - if(m.find()) - { - fileName = m.group(1); - } - } - else if(fileName != null) - { - OutputStream stream = new FileOutputStream(fileName); - if(digestMD5 != null) - stream = new DigestOutputStream(stream, digestMD5); - writer = new OutputStreamWriter(stream, streamCharset); - } - else - throw new RuntimeException("Name of uploaded file not found"); - } - else - { - // Read data from stream - int readLength = Math.min(contentLength, buffer.length); - readLength = in.read(buffer, 0, readLength); - if(readLength < 0) - break; - contentLength -= readLength; - // Find boundary string - String curBuffer = new String(buffer, 0, readLength); - String bothBuffers = prevBuffer + curBuffer; - int boundaryPos = bothBuffers.indexOf(boundary); - if(boundaryPos == -1) - { - writer.write(prevBuffer, 0, prevBuffer.length()); - prevBuffer = curBuffer; - } - else - { - writer.write(bothBuffers, 0, boundaryPos); - break; - } - } - // Write stats - System.out.print("Read: " + (totalLength - contentLength) - + " Remains: " + contentLength + " Total: " + totalLength - + " bytes \r"); - } - System.out.println("Done "); - writer.close(); - // Finalize digest calculation - byte[] md5Sum = digestMD5.digest(); - StringBuffer md5SumString = new StringBuffer(); - for(int n = 0; n < md5Sum.length; ++ n) - md5SumString.append(printByte(md5Sum[n])); - // Output client info - String answer = httpHeader + "

Upload completed, " + totalLength - + " bytes, MD5 sum: " + md5SumString.toString() + "" - + "

Next file\r\n\r\n"; - out.write(answer.getBytes()); - } - } - - private static String printByte(byte b) - { - int bi = ((int)b) & 0xFF; - if(bi < 16) - return "0" + Integer.toHexString(bi); - else - return Integer.toHexString(bi); - } - - public static void main(String[] args) - { - try - { - if(args.length < 1) - { - System.out.println("Usage: UploadServer "); - int port = 8081; - UploadServer server = new UploadServer(port); - server.start(); - return; - } - UploadServer server = new UploadServer(Integer.parseInt(args[0])); - server.start(); - } - catch(Exception e) - { - System.err.println("Error in main"); - e.printStackTrace(); - } - } -} diff --git a/target/classes/ru/molokoin/ExchangeServer.class b/target/classes/ru/molokoin/ExchangeServer.class index 5240a0c..5a1271e 100644 Binary files a/target/classes/ru/molokoin/ExchangeServer.class and b/target/classes/ru/molokoin/ExchangeServer.class differ diff --git a/target/classes/ru/molokoin/MainFrameController.class b/target/classes/ru/molokoin/MainFrameController.class index 666da0b..5f19190 100644 Binary files a/target/classes/ru/molokoin/MainFrameController.class and b/target/classes/ru/molokoin/MainFrameController.class differ diff --git a/target/classes/ru/molokoin/SystemInfo.class b/target/classes/ru/molokoin/SystemInfo.class deleted file mode 100644 index f64b165..0000000 Binary files a/target/classes/ru/molokoin/SystemInfo.class and /dev/null differ diff --git a/target/classes/ru/molokoin/UploadServer.class b/target/classes/ru/molokoin/example/UploadServer.class similarity index 97% rename from target/classes/ru/molokoin/UploadServer.class rename to target/classes/ru/molokoin/example/UploadServer.class index 7b45696..f55fa79 100644 Binary files a/target/classes/ru/molokoin/UploadServer.class and b/target/classes/ru/molokoin/example/UploadServer.class differ