-
Notifications
You must be signed in to change notification settings - Fork 1
/
ServerThread.java
72 lines (62 loc) · 1.99 KB
/
ServerThread.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
import java.net.*;
import java.io.*;
import java.util.Scanner;
public class ServerThread extends Thread
{
private Socket socket = null;
public ServerThread(Socket aSocket)
{
super("ServerThread");
socket = aSocket;
System.out.println("Starting new thread...");
}
public void run()
{
System.out.println("Accepted connection : " + socket);
try
{
Scanner scan = new Scanner(socket.getInputStream());
// get request
String filename = scan.nextLine();
System.out.println("Filename: " + filename);
File file = new File(filename);
// send response
PrintWriter out = null;
out = new PrintWriter(socket.getOutputStream(), true);
boolean ok = false;
if (!file.exists())
out.println("Error: file doesn't exist.");
else if (!file.isFile())
out.println("Error: not a file.");
else if (!file.canRead())
out.println("Error: can't read from file.");
else
{
out.println("OKGO");
ok = true;
}
if (!ok)
return;
// setup streams
FileInputStream fin = new FileInputStream(filename);
BufferedInputStream bin = new BufferedInputStream(fin);
BufferedOutputStream os = new BufferedOutputStream(
socket.getOutputStream());
// write file to socket
System.out.println("Sending Files...");
int count;
byte[] buffer = new byte[8192];
while ((count = fin.read(buffer)) > 0)
os.write(buffer, 0, count);
// cleanup
bin.close();
os.close();
fin.close();
System.out.println("File transfer complete.");
}
catch (IOException e)
{
e.printStackTrace();
}
}
}