|
| 1 | +/* |
| 2 | + * Copyright (C) 2019 Iago Colodetti |
| 3 | + * |
| 4 | + * This program is free software; you can redistribute it and/or |
| 5 | + * modify it under the terms of the GNU General Public License |
| 6 | + * as published by the Free Software Foundation; either version 2 |
| 7 | + * of the License, or (at your option) any later version. |
| 8 | + * |
| 9 | + * This program is distributed in the hope that it will be useful, |
| 10 | + * but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 11 | + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| 12 | + * GNU General Public License for more details. |
| 13 | + * |
| 14 | + * You should have received a copy of the GNU General Public License |
| 15 | + * along with this program; if not, write to the Free Software |
| 16 | + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. |
| 17 | + */ |
| 18 | +package br.com.iagocolodetti.transferirarquivo; |
| 19 | + |
| 20 | +import br.com.iagocolodetti.transferirarquivo.exception.ClientConnectException; |
| 21 | +import br.com.iagocolodetti.transferirarquivo.exception.SendFileException; |
| 22 | +import java.io.DataInputStream; |
| 23 | +import java.io.DataOutputStream; |
| 24 | +import java.io.File; |
| 25 | +import java.io.FileInputStream; |
| 26 | +import java.io.FileNotFoundException; |
| 27 | +import java.io.FileOutputStream; |
| 28 | +import java.io.IOException; |
| 29 | +import java.io.InputStream; |
| 30 | +import java.io.OutputStream; |
| 31 | +import java.net.Socket; |
| 32 | +import java.util.List; |
| 33 | +import java.util.regex.Pattern; |
| 34 | + |
| 35 | +/** |
| 36 | + * |
| 37 | + * @author iagocolodetti |
| 38 | + */ |
| 39 | +public class Client { |
| 40 | + |
| 41 | + private final int MIN_PORT = 0; |
| 42 | + private final int MAX_PORT = 65535; |
| 43 | + |
| 44 | + private MainGUI mainGUI = null; |
| 45 | + |
| 46 | + private Socket socket = null; |
| 47 | + |
| 48 | + private volatile boolean connected = false; |
| 49 | + |
| 50 | + private boolean receivingFile = false; |
| 51 | + private Thread sendingFile = null; |
| 52 | + |
| 53 | + private final int CONNECT_TIMEOUT = 5000; |
| 54 | + private final int MAX_RECONNECT_TRIES = 5; |
| 55 | + private final int WAIT_TO_RECONNECT = 500; |
| 56 | + private final int WAIT_AFTER_SEND = 2000; |
| 57 | + private final int WAIT_AFTER_SEND_LOOP = 10; |
| 58 | + |
| 59 | + public Client(MainGUI mainGUI) { |
| 60 | + this.mainGUI = mainGUI; |
| 61 | + } |
| 62 | + |
| 63 | + public void connect(String ip, int port, String dir) throws ClientConnectException { |
| 64 | + if (ip.isEmpty()) { |
| 65 | + throw new ClientConnectException("Entre com o IP do servidor."); |
| 66 | + } |
| 67 | + if (!Pattern.compile("^(([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\.){3}([01]?\\d\\d?|2[0-4]\\d|25[0-5])$").matcher(ip).matches()) { |
| 68 | + throw new ClientConnectException("Digite um IP válido."); |
| 69 | + } |
| 70 | + if (port < MIN_PORT || port > MAX_PORT) { |
| 71 | + throw new ClientConnectException("A porta deve ser no mínimo " + MIN_PORT + " e no máximo " + MAX_PORT + "."); |
| 72 | + } |
| 73 | + if (dir.isEmpty()) { |
| 74 | + throw new ClientConnectException("Selecione um diretório para recebimento de arquivos.", 1); |
| 75 | + } else { |
| 76 | + try { |
| 77 | + new File(dir).mkdirs(); |
| 78 | + } catch (SecurityException ex) { |
| 79 | + throw new ClientConnectException("O diretório selecionado não existe e não foi possível criá-lo.\nSelecione outro diretório ou tente iniciar a aplicação como administrador."); |
| 80 | + } |
| 81 | + } |
| 82 | + mainGUI.cltConnecting(); |
| 83 | + Thread t = new Thread(new ClientConnect(ip, port, dir)); |
| 84 | + t.start(); |
| 85 | + } |
| 86 | + |
| 87 | + public void disconnect() { |
| 88 | + try { |
| 89 | + connected = false; |
| 90 | + if (socket != null && !socket.isClosed()) { |
| 91 | + socket.close(); |
| 92 | + } |
| 93 | + } catch (IOException ex) { |
| 94 | + ex.printStackTrace(); |
| 95 | + } finally { |
| 96 | + socket = null; |
| 97 | + mainGUI.cltDisconnected(); |
| 98 | + } |
| 99 | + } |
| 100 | + |
| 101 | + public void sendFiles(List<File> files) throws SendFileException { |
| 102 | + if (!isSocketConnected()) { |
| 103 | + throw new SendFileException("É necessário estar conectado a um servidor para enviar arquivos."); |
| 104 | + } |
| 105 | + if (files == null || files.isEmpty()) { |
| 106 | + throw new SendFileException("Selecione pelo menos um arquivo para enviar."); |
| 107 | + } |
| 108 | + if (receivingFile || sendingFiles()) { |
| 109 | + throw new SendFileException("Uma transferência já está em andamento."); |
| 110 | + } |
| 111 | + sendingFile = new Thread(new SendFiles(files)); |
| 112 | + sendingFile.start(); |
| 113 | + } |
| 114 | + |
| 115 | + public boolean sendingFiles() { |
| 116 | + return (sendingFile != null && sendingFile.isAlive()); |
| 117 | + } |
| 118 | + |
| 119 | + private boolean isSocketConnected() { |
| 120 | + return (socket != null && !socket.isClosed() && socket.isConnected()); |
| 121 | + } |
| 122 | + |
| 123 | + private void threadSleep(int ms) { |
| 124 | + try { |
| 125 | + Thread.sleep(ms); |
| 126 | + } catch (InterruptedException ex) { |
| 127 | + ex.printStackTrace(); |
| 128 | + } |
| 129 | + } |
| 130 | + |
| 131 | + private class ClientConnect implements Runnable { |
| 132 | + |
| 133 | + private final String ip; |
| 134 | + private final int port; |
| 135 | + private final String dir; |
| 136 | + |
| 137 | + public ClientConnect(String ip, int port, String dir) { |
| 138 | + connected = true; |
| 139 | + this.ip = ip; |
| 140 | + this.port = port; |
| 141 | + this.dir = dir; |
| 142 | + } |
| 143 | + |
| 144 | + @Override |
| 145 | + public void run() { |
| 146 | + while (connected) { |
| 147 | + receivingFile = false; |
| 148 | + if (!isSocketConnected()) { |
| 149 | + threadSleep(socket == null ? 0 : WAIT_TO_RECONNECT); |
| 150 | + int tries = 0; |
| 151 | + while (connected && tries < MAX_RECONNECT_TRIES) { |
| 152 | + try { |
| 153 | + socket = null; |
| 154 | + socket = new Socket(ip, port); |
| 155 | + mainGUI.cltConnected(); |
| 156 | + break; |
| 157 | + } catch (IllegalArgumentException ex) { |
| 158 | + Utils.msgBoxError(mainGUI, "IP e/ou porta incorreto(s)."); |
| 159 | + disconnect(); |
| 160 | + ex.printStackTrace(); |
| 161 | + break; |
| 162 | + } catch (IOException ex) { |
| 163 | + tries++; |
| 164 | + ex.printStackTrace(); |
| 165 | + threadSleep(CONNECT_TIMEOUT); |
| 166 | + } |
| 167 | + } |
| 168 | + if (tries == MAX_RECONNECT_TRIES) { |
| 169 | + Utils.msgBoxError(mainGUI, "Não foi possível conectar-se a esse servidor."); |
| 170 | + disconnect(); |
| 171 | + } |
| 172 | + } |
| 173 | + if (connected) { |
| 174 | + InputStream is = null; |
| 175 | + DataInputStream dis = null; |
| 176 | + OutputStream out = null; |
| 177 | + try { |
| 178 | + is = socket.getInputStream(); |
| 179 | + dis = new DataInputStream(is); |
| 180 | + String[] data = dis.readUTF().split(Pattern.quote("|")); |
| 181 | + receivingFile = true; |
| 182 | + threadSleep(1000); |
| 183 | + String newFileName = data[0]; |
| 184 | + for (int i = 1; new File(dir + newFileName).exists(); i++) { |
| 185 | + newFileName = data[0].substring(0, data[0].lastIndexOf(".")) + "(" + i + ")" + data[0].substring(data[0].lastIndexOf(".")); |
| 186 | + } |
| 187 | + long size = Long.parseLong(data[1]); |
| 188 | + long sizekb = (data[1].equals("0") ? 1 : (size / 1024)); |
| 189 | + sizekb = (sizekb == 0 ? 1 : sizekb); |
| 190 | + is = socket.getInputStream(); |
| 191 | + out = new FileOutputStream(dir + newFileName); |
| 192 | + mainGUI.cltSetStatus("Recebendo Arquivo"); |
| 193 | + mainGUI.cltAddTextAreaLog("Recebendo Arquivo: \"" + newFileName + "\"."); |
| 194 | + mainGUI.cltSetProgressPainted(true); |
| 195 | + byte[] buffer = new byte[1024]; |
| 196 | + long receivedBytes = 0; |
| 197 | + int count; |
| 198 | + long kb = 0; |
| 199 | + int progress; |
| 200 | + while ((count = is.read(buffer)) > 0) { |
| 201 | + out.write(buffer, 0, count); |
| 202 | + receivedBytes += count; |
| 203 | + progress = (int)(++kb * 100 / sizekb); |
| 204 | + mainGUI.cltSetProgress(progress < 100 ? progress : 100); |
| 205 | + } |
| 206 | + if (receivedBytes == size) { |
| 207 | + mainGUI.cltAddTextAreaLog("Arquivo \"" + newFileName + "\" recebido com sucesso."); |
| 208 | + } else { |
| 209 | + mainGUI.cltAddTextAreaLog("Arquivo \"" + newFileName + "\" corrompido durante o recebimento."); |
| 210 | + disconnect(); |
| 211 | + Utils.msgBoxError(mainGUI, "Conexão com o servidor perdida."); |
| 212 | + } |
| 213 | + } catch (FileNotFoundException ex) { |
| 214 | + if (connected && !sendingFiles()) { |
| 215 | + disconnect(); |
| 216 | + Utils.msgBoxError(mainGUI, "O diretório selecionado não foi encontrado."); |
| 217 | + ex.printStackTrace(); |
| 218 | + } |
| 219 | + } catch (IOException ex) { |
| 220 | + if (connected && !sendingFiles()) { |
| 221 | + disconnect(); |
| 222 | + Utils.msgBoxError(mainGUI, "Conexão com o servidor perdida."); |
| 223 | + ex.printStackTrace(); |
| 224 | + } |
| 225 | + } finally { |
| 226 | + try { |
| 227 | + if (out != null) { |
| 228 | + out.close(); |
| 229 | + } |
| 230 | + if (is != null) { |
| 231 | + is.close(); |
| 232 | + } |
| 233 | + if (dis != null) { |
| 234 | + dis.close(); |
| 235 | + } |
| 236 | + if (socket != null) { |
| 237 | + socket.close(); |
| 238 | + } |
| 239 | + } catch (IOException ex) { |
| 240 | + ex.printStackTrace(); |
| 241 | + } finally { |
| 242 | + mainGUI.cltSetStatus(""); |
| 243 | + mainGUI.cltSetProgress(0); |
| 244 | + mainGUI.cltSetProgressPainted(false); |
| 245 | + } |
| 246 | + } |
| 247 | + } |
| 248 | + } |
| 249 | + } |
| 250 | + } |
| 251 | + |
| 252 | + private class SendFiles implements Runnable { |
| 253 | + |
| 254 | + private final List<File> files; |
| 255 | + |
| 256 | + public SendFiles(List<File> files) { |
| 257 | + this.files = files; |
| 258 | + } |
| 259 | + |
| 260 | + @Override |
| 261 | + public void run() { |
| 262 | + for (File file : files) { |
| 263 | + int loop = 0; |
| 264 | + while (!isSocketConnected() && loop < WAIT_AFTER_SEND_LOOP) { |
| 265 | + loop++; |
| 266 | + threadSleep(WAIT_AFTER_SEND); |
| 267 | + } |
| 268 | + if (loop == WAIT_AFTER_SEND_LOOP) { |
| 269 | + Utils.msgBoxError(mainGUI, "Não foi possível enviar os arquivos restantes."); |
| 270 | + break; |
| 271 | + } |
| 272 | + if (file.exists()) { |
| 273 | + DataOutputStream dos = null; |
| 274 | + FileInputStream fis = null; |
| 275 | + OutputStream out = null; |
| 276 | + try { |
| 277 | + dos = new DataOutputStream(socket.getOutputStream()); |
| 278 | + dos.writeUTF(file.getName() + "|" + file.length()); |
| 279 | + threadSleep(1000); |
| 280 | + fis = new FileInputStream(file); |
| 281 | + out = socket.getOutputStream(); |
| 282 | + mainGUI.cltSetStatus("Enviando Arquivo"); |
| 283 | + mainGUI.cltAddTextAreaLog("Enviando Arquivo: \"" + file.getName() + "\"."); |
| 284 | + mainGUI.cltSetProgressPainted(true); |
| 285 | + byte[] buffer = new byte[1024]; |
| 286 | + long sendedBytes = 0; |
| 287 | + int count; |
| 288 | + long sizekb = (file.length() / 1024); |
| 289 | + sizekb = (sizekb == 0 ? 1 : sizekb); |
| 290 | + long kb = 0; |
| 291 | + int progress; |
| 292 | + while ((count = fis.read(buffer)) > 0) { |
| 293 | + out.write(buffer, 0, count); |
| 294 | + sendedBytes += count; |
| 295 | + progress = (int)(++kb * 100 / sizekb); |
| 296 | + mainGUI.cltSetProgress(progress < 100 ? progress : 100); |
| 297 | + } |
| 298 | + if (sendedBytes == file.length()) { |
| 299 | + mainGUI.cltAddTextAreaLog("Arquivo \"" + file.getName() + "\" enviado com sucesso."); |
| 300 | + } else { |
| 301 | + mainGUI.cltAddTextAreaLog("Arquivo \"" + file.getName() + "\" corrompido durante o envio."); |
| 302 | + } |
| 303 | + } catch (IOException ex) { |
| 304 | + if (connected) { |
| 305 | + disconnect(); |
| 306 | + Utils.msgBoxError(mainGUI, "Conexão com o servidor perdida."); |
| 307 | + ex.printStackTrace(); |
| 308 | + } |
| 309 | + } finally { |
| 310 | + try { |
| 311 | + if (out != null) { |
| 312 | + out.close(); |
| 313 | + } |
| 314 | + if (fis != null) { |
| 315 | + fis.close(); |
| 316 | + } |
| 317 | + if (dos != null) { |
| 318 | + dos.close(); |
| 319 | + } |
| 320 | + if (socket != null) { |
| 321 | + socket.close(); |
| 322 | + } |
| 323 | + } catch (IOException ex) { |
| 324 | + ex.printStackTrace(); |
| 325 | + } finally { |
| 326 | + mainGUI.cltSetStatus(""); |
| 327 | + mainGUI.cltSetProgress(0); |
| 328 | + mainGUI.cltSetProgressPainted(false); |
| 329 | + } |
| 330 | + } |
| 331 | + } else { |
| 332 | + mainGUI.cltAddTextAreaLog("Arquivo: \"" + file.getName() + "\" não foi encontrado."); |
| 333 | + } |
| 334 | + threadSleep(WAIT_AFTER_SEND); |
| 335 | + } |
| 336 | + } |
| 337 | + } |
| 338 | +} |
0 commit comments