-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathFileSender.java
More file actions
52 lines (46 loc) · 1.69 KB
/
FileSender.java
File metadata and controls
52 lines (46 loc) · 1.69 KB
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
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
/**
* Sends a file to the server over the dedicated file transfer port (chatPort + 1).
* Protocol:
* First line: FILE <filename> <size> <targetUserOrStar>
* Followed immediately by <size> raw bytes of the file.
*/
public class FileSender {
private final String host;
private final int filePort;
public FileSender(String host, int filePort) {
this.host = host;
this.filePort = filePort;
}
public void sendFile(String targetUserOrStar, String path) throws IOException {
File file = new File(path);
if (!file.exists() || !file.isFile()) {
throw new IOException("File not found: " + path);
}
String filename = file.getName();
long size = file.length();
try (Socket socket = new Socket(host, filePort);
PrintWriter headerOut = new PrintWriter(socket.getOutputStream(), true);
OutputStream dataOut = socket.getOutputStream();
FileInputStream fis = new FileInputStream(file)) {
headerOut.println("FILE " + filename + " " + size + " " + targetUserOrStar);
headerOut.flush();
byte[] buf = new byte[8192];
long sent = 0;
int read;
while ((read = fis.read(buf)) != -1) {
dataOut.write(buf, 0, read);
sent += read;
}
dataOut.flush();
if (sent != size) {
throw new IOException("Mismatch in sent size. Expected " + size + " but sent " + sent);
}
}
}
}