This repository has been archived by the owner on Jul 6, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 11
/
LogServer.java
63 lines (60 loc) · 2.18 KB
/
LogServer.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
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.atomic.AtomicLong;
/**
* Created by chen on 2017/7/15.
*/
public class LogServer {
public static void main(String []args){
try {
ServerSocket serverSocket = new ServerSocket(9090);
AtomicLong mCountLogs = new AtomicLong(0);
while (true) {
System.out.println("start write log"+serverSocket.getLocalSocketAddress().toString());
Socket socket = serverSocket.accept();
System.out.println("start write log");
new Thread(new LogWriter(mCountLogs.getAndDecrement(), socket)).start();
}
} catch (IOException e) {
e.printStackTrace();
}
}
static class LogWriter implements Runnable{
private long mLogSerial;
private Socket mSocket;
public LogWriter(long logSerial,Socket socket) {
this.mLogSerial = logSerial;
this.mSocket = socket;
}
@Override
public void run() {
try {
File destLogFile = new File("D:\\logs"+mLogSerial+".txt");
destLogFile.createNewFile();
InputStream ins = mSocket.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(ins));
OutputStream outputStream = new FileOutputStream(destLogFile);
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream));
String line;
while(mSocket.isConnected() && (line = reader.readLine()) != null){
System.out.println("line is " +line);
writer.write(line);
}
reader.close();
writer.flush();
writer.close();
System.out.println("end write log");
} catch (IOException e) {
e.printStackTrace();
}
finally {
try {
mSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}