-
Notifications
You must be signed in to change notification settings - Fork 0
/
Connection.java
59 lines (36 loc) · 1.15 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
package com.codegym.task.task30.task3008;
import java.io.Closeable;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.net.SocketAddress;
public class Connection implements Closeable {
private final Socket socket;
private final ObjectOutputStream out;
private final ObjectInputStream in;
public Connection(Socket socket) throws IOException {
this.socket = socket;
this.out = new ObjectOutputStream(socket.getOutputStream());
this.in = new ObjectInputStream(socket.getInputStream());
}
public void send(Message message) throws IOException {
synchronized (out) {
out.writeObject(message);
}
}
public Message receive() throws IOException,ClassNotFoundException {
synchronized (in) {
return (Message) in.readObject();
}
}
public SocketAddress getRemoteSocketAddress() {
return socket.getRemoteSocketAddress();
}
@Override
public void close() throws IOException {
in.close();
out.close();
socket.close();
}
}