-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathFileSend.java
72 lines (67 loc) · 2.34 KB
/
FileSend.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package net;
import java.io.*;
/**
* @author lbsilva
*/
public class FileSend extends FileTransmission {
/**
* Sends a file to a certain Id
*
* @param path - Path of the file to be sent
* @param id - destination id
* @throws IOException - Some network failure
*/
public FileSend(String path, String id) throws IOException {
super(path);
if (!file.exists()) {
throw new FileNotFoundException("File\n\"" + path + "\"\nnot found.");
}
handshake(id);
}
/**
* Handshake process with the server
*
* @param id - the id
* @throws IOException - Some network failure
*/
private void handshake(String id) throws IOException {
new Transmission(sslSocket).sendText("SENDER");
if (!new Transmission(sslSocket).readText().equals("RECEPTOR_ID?"))
throw new HandshakeException("Handshake error");
new Transmission(sslSocket).sendText(id);
String result = new Transmission(sslSocket).readText();
if (result.equals("NOT_A_VALID_ID")) {
throw new HandshakeException("Selected ID not waiting for a file.");
} else if (!result.equals("ID_IS_VALID")) {
throw new HandshakeException("Handshake error");
}
}
@Override
public void start() {
FileInputStream fis = null;
BufferedInputStream bis = null;
OutputStream os = null;
try {
fis = new FileInputStream(file);
bis = new BufferedInputStream(fis);
os = sslSocket.getOutputStream();
int count;
byte[] buffer = new byte[BUFFER_SIZE];
while (!canceled && (count = bis.read(buffer)) > 0) {
os.write(buffer, 0, count);
}
os.flush(); // It's a bit redundant but just in case
status = canceled ? "Canceled" : "Sent\n\"" + file.getAbsolutePath() + "\"\n(" + file.length() + " bytes)";
} catch (IOException exception) {
canceled = true;
status = "Either canceled or some error occurred.";
} finally {
finish(fis, bis, os, sslSocket);
}
}
}