-
Notifications
You must be signed in to change notification settings - Fork 1
/
Connection.java
67 lines (57 loc) · 1.75 KB
/
Connection.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
import java.io.*;
import java.net.Socket;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class Connection implements AutoCloseable {
private final DataInputStream in;
private final DataOutputStream out;
private final Lock rl = new ReentrantLock();
private final Lock wl = new ReentrantLock();
public Connection(Socket socket) throws IOException {
this.in = new DataInputStream(new BufferedInputStream(socket.getInputStream()));
this.out = new DataOutputStream(new BufferedOutputStream(socket.getOutputStream()));
}
public DataInputStream getIn() {
return in;
}
public DataOutputStream getOut() {
return out;
}
public void send(Pdu frame) throws IOException {
try {
wl.lock();
this.out.writeInt(frame.tag);
this.out.writeUTF(frame.nome);
this.out.writeInt(frame.data.length);
this.out.write(frame.data);
this.out.flush();
} finally {
wl.unlock();
}
}
public void send(int tag, String nome, byte[] data) throws IOException {
this.send(new Pdu(tag, nome, data));
}
public Pdu receive() throws IOException {
int tag;
String username;
byte[] data;
try {
rl.lock();
tag = this.in.readInt();
username = this.in.readUTF();
int n = this.in.readInt();
data = new byte[n];
this.in.readFully(data);
} finally {
rl.unlock();
}
return new Pdu
(tag, username, data);
}
@Override
public void close() throws IOException {
this.in.close();
this.out.close();
}
}