-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathFileServer.java
More file actions
executable file
·83 lines (59 loc) · 1.79 KB
/
FileServer.java
File metadata and controls
executable file
·83 lines (59 loc) · 1.79 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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
package dchat;
import java.net.*;
import java.io.*;
import java.util.logging.Level;
import java.util.logging.Logger;
public class FileServer extends Thread { // GET : SEND
private ServerSocket sock = null;
private String filename;
public FileServer(String filename)
{
this.filename = filename;
try {
sock = new ServerSocket();
sock.bind(null); // associates socket with local address
} catch (IOException ex) {
Logger.getLogger(FileServer.class.getName()).log(Level.SEVERE, null, ex);
}
}
public int getPort()
{
return sock.getLocalPort();
}
public void run()
{
Socket clientSocket;
DataInputStream bufRead = null;
DataOutputStream bufWriter = null;
int nbytes = 0;
byte[] cbuf = new byte[2048];
FileOutputStream fileOut = null;
try {
fileOut = new FileOutputStream(filename);
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
clientSocket = sock.accept(); // waits for new connections
bufRead = new DataInputStream(clientSocket.getInputStream());
bufWriter = new DataOutputStream(fileOut);
while ((nbytes = bufRead.read(cbuf)) != -1) {
bufWriter.write(cbuf, 0, nbytes);
}
bufWriter.flush();
} catch (IOException ex) {
Logger.getLogger(FileServer.class.getName()).log(Level.SEVERE, null, ex);
}
System.out.println(bufWriter.toString());
try {
sock.close();
bufWriter.close();
bufRead.close();
fileOut.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}