-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDuplexer.java
60 lines (52 loc) · 1.57 KB
/
Duplexer.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
/**
* A shortcut to create PrinterWriter, BufferedReader for a socket connetction.
* file: Duplexer.java
* Author: Abdulmalik Banaser
*/
import java.io.*;
import java.net.Socket;
public class Duplexer implements AutoCloseable {
private final Socket socket;
private final PrintWriter writer;
private final BufferedReader reader;
/**
* constructor to creat a printerWriter and BufferedReader for a given socket.
* @param socket socket connection
* @throws IOException
*/
public Duplexer(Socket socket) throws IOException {
this.socket = socket;
InputStream input = socket.getInputStream();
InputStreamReader iReader = new InputStreamReader(input);
reader = new BufferedReader(iReader);
OutputStream output = socket.getOutputStream();
writer = new PrintWriter(output);
}
/**
* A method to send the given string to the other end of the socket connection
* @param message the message to send
*/
public void send(String message) {
writer.println(message);
writer.flush();
}
/**
* A method that return the string received
* @return the received message form the other side of the connection
* @throws IOException
*/
public String receive() throws IOException {
return reader.readLine();
}
@Override
public void close() throws Exception {
socket.close();
}
/**
* return the socket that the duplexer was built on
* @return
*/
public Socket getSocket() {
return socket;
}
}