-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSocketBase.java
More file actions
53 lines (47 loc) · 1.76 KB
/
Copy pathSocketBase.java
File metadata and controls
53 lines (47 loc) · 1.76 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
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;
public class SocketBase implements AutoCloseable {
protected Socket socket;
protected InputStreamReader inputStreamReader;
protected OutputStreamWriter outputStreamWriter;
protected BufferedReader readBuffer;
protected BufferedWriter writeBuffer;
protected SocketBase(Socket socket) throws IOException {
this.socket = socket;
this.inputStreamReader = new InputStreamReader(socket.getInputStream());
this.outputStreamWriter = new OutputStreamWriter(socket.getOutputStream());
this.readBuffer = new BufferedReader(inputStreamReader);
this.writeBuffer = new BufferedWriter(outputStreamWriter);
}
public void close() {
try {
if (this.socket != null) {
this.socket.close();
}
if (this.inputStreamReader != null) {
this.inputStreamReader.close();
}
if (this.outputStreamWriter != null) {
this.outputStreamWriter.close();
}
if (this.readBuffer != null) {
this.readBuffer.close();
}
if (this.writeBuffer != null) {
this.writeBuffer.close();
}
} catch (IOException e) {
System.out.println(this.getClass().getSimpleName() + ".shutdown(): Encountered an error while shutting down:");
e.printStackTrace();
}
}
protected void sendMessage(final String msg) throws IOException {
this.writeBuffer.write(msg);
this.writeBuffer.newLine();
this.writeBuffer.flush();
}
}