-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathServer.java
86 lines (79 loc) · 2.24 KB
/
Server.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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
package fileTransfer;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
public class Server {
public final static int PORT = 10002;
//receive directory path
public final static String DIR = "C:\\Users\\shiweigang\\Desktop\\";
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
ServerSocket server = new ServerSocket(PORT);
while(true){
System.out.println("waiting for connection....");
Socket socket = server.accept();
InputStream is = socket.getInputStream();
int type = is.read();
if(type == 0){//Îı¾
receiveText(is);
}else if(type == 1){//Îļþ
receiveFile(is);
}else{
System.err.println("error data format!");
is.close();
}
}
}
public static void receiveText(InputStream is) throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(is));
StringBuffer sb = new StringBuffer();
String temp = null;
while((temp = br.readLine()) != null){
sb.append(temp);
}
br.close();
System.out.println("=============TEXT AREA===============");
System.out.println(sb);
System.out.println("=====================================");
}
public static void receiveFile(InputStream is) throws IOException{
int fileNameL = is.read();
if(fileNameL == -1){
System.err.println("empty data packet");
return;
}
byte fileNameB [] = new byte[fileNameL];
is.read(fileNameB);
String fileName = new String(fileNameB);
File file = new File(DIR +fileName);
StringBuffer temp = null;
if(file.exists()){
int index = fileName.length();
if(fileName.contains(".")){
index = fileName.indexOf(".");
}
for(int i = 0; true; i++){
temp = new StringBuffer(fileName);
temp.insert(index, "("+i+")");
file = new File(DIR + temp.toString());
if(!file.exists()){
break;
}
}
}
FileOutputStream fo = new FileOutputStream(file);
byte bytes [] = new byte[1024];
int length = 0;
while((length = is.read(bytes)) != -1){
fo.write(bytes, 0, length);
}
is.close();
fo.close();
System.out.println("file received successfully");
}
}