-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTCPServer.java
117 lines (107 loc) · 3.23 KB
/
TCPServer.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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
import java.beans.XMLEncoder;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
public class TCPServer
implements Runnable,
ModelListener {
static int counter = 2;
protected ServerSocket serverSocket;
private ArrayList<Socket> clientList = null;
protected int myPort;
Canvas canvas = null;
public void decodeAll() {
for (Socket sock : this.clientList) {
try {
try {
TCPClient.decode(sock.getInputStream());
}
catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
catch (IOException e) {
e.printStackTrace();
}
}
}
public void addClient(Socket s) {
this.clientList.add(s);
}
public TCPServer(int port, Canvas c) {
try {
this.clientList = new ArrayList();
this.myPort = port;
this.serverSocket = new ServerSocket(this.myPort);
this.canvas = c;
}
catch (Exception e) {
System.err.println(e.getMessage());
System.exit(1);
}
}
@Override
public void run() {
try {
do {
Socket clientSocket = this.serverSocket.accept();
this.addClient(clientSocket);
this.originalNotification(clientSocket, this.canvas.getShapeModelArray());
} while (true);
}
catch (IOException ioe) {
System.err.println("Failed to accept socket, " + ioe);
System.exit(1);
return;
}
}
public void notifyAll(String action, DShapeModel a) {
for (Socket sock : this.clientList) {
this.notify(sock, action, a);
}
}
public void loadNotification(ArrayList<DShapeModel> ar) {
for (Socket s : this.clientList) {
this.notify(s, "deleteShapes", new DRectModel());
for (DShapeModel f : ar) {
this.notify(s, "add", f);
}
}
}
public void originalNotification(Socket s, ArrayList<DShapeModel> ar) {
for (DShapeModel f : ar) {
this.notify(s, "add", f);
}
}
public void notify(Socket sock, String action, DShapeModel a) {
if (a.getId() == 0) {
a.setId(counter++);
}
a.remColors();
ObjectOutputStream os = null;
try {
ByteArrayOutputStream memStream = new ByteArrayOutputStream();
XMLEncoder encoder = new XMLEncoder(memStream);
encoder.writeObject(action);
encoder.writeObject(a);
encoder.close();
String res = memStream.toString();
os = new ObjectOutputStream(sock.getOutputStream());
os.writeObject(res);
os.flush();
}
catch (IOException e1) {
e1.printStackTrace();
}
}
@Override
public void modelChanged(DShapeModel model) {
this.notifyAll("changed", model);
}
}