-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathBxServerSocket.java
97 lines (87 loc) · 1.93 KB
/
BxServerSocket.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
87
88
89
90
91
92
93
94
95
96
import java.io.DataInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Random;
/**
* 接收文件服务
* @author admin_Hzw
*
*/
public class BxServerSocket {
/**
* 工程main方法
* @param args
*/
{
try {
final ServerSocket server = new ServerSocket(48123);
Thread th = new Thread(new Runnable()
{
public void run() {
while (true) {
try {
System.out.println("开始监听...");
/*
* 如果没有访问它会自动等待
*/
Socket socket = server.accept();
System.out.println("有链接");
receiveFile(socket);
} catch (Exception e) {
System.out.println("服务器异常");
e.printStackTrace();
}
}}
});
th.run(); //启动线程运行
} catch (Exception e) {
e.printStackTrace();
}
}
public void run() {
}
/**
* 接收文件方法
* @param socket
* @throws IOException
*/
public static void receiveFile(Socket socket) throws IOException {
byte[] inputByte = null;
int length = 0;
DataInputStream dis = null;
FileOutputStream fos = null;
String filePath = "D:/temp/"+GetDate.getDate()+"SJ"+new Random().nextInt(10000)+".zip";
try {
try {
dis = new DataInputStream(socket.getInputStream());
File f = new File("D:/temp");
if(!f.exists()){
f.mkdir();
}
/*
* 文件存储位置
*/
fos = new FileOutputStream(new File(filePath));
inputByte = new byte[1024];
System.out.println("开始接收数据...");
while ((length = dis.read(inputByte, 0, inputByte.length)) > 0) {
fos.write(inputByte, 0, length);
fos.flush();
}
System.out.println("完成接收:"+filePath);
} finally {
if (fos != null)
fos.close();
if (dis != null)
dis.close();
if (socket != null)
socket.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}