forked from processing/processing4
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathServer.java
More file actions
377 lines (324 loc) · 9.69 KB
/
Server.java
File metadata and controls
377 lines (324 loc) · 9.69 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
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
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
/* -*- mode: java; c-basic-offset: 2; indent-tabs-mode: nil -*- */
/*
Server - basic network server implementation
Part of the Processing project - http://processing.org
Copyright (c) 2004-2007 Ben Fry and Casey Reas
The previous version of this code was developed by Hernando Barragan
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General
Public License along with this library; if not, write to the
Free Software Foundation, Inc., 59 Temple Place, Suite 330,
Boston, MA 02111-1307 USA
*/
package processing.net;
import processing.core.*;
import java.io.*;
import java.lang.reflect.*;
import java.net.*;
/**
*
* A server sends and receives data to and from its associated clients
* (other programs connected to it). When a server is started, it begins
* listening for connections on the port specified by the <b>port</b>
* parameter. Computers have many ports for transferring data and some are
* commonly used so be sure to not select one of these. For example, web
* servers usually use port 80 and POP mail uses port 110.
*
* @webref server
* @usage application
* @webBrief The server class is used to create server objects which send
* and receives data to and from its associated clients (other programs connected to it)
* @instanceName server any variable of type Server
*/
public class Server implements Runnable {
PApplet parent;
Method serverEventMethod;
volatile Thread thread;
ServerSocket server;
int port;
protected final Object clientsLock = new Object[0];
/** Number of clients currently connected. */
public int clientCount;
/** Array of client objects, useful length is determined by clientCount. */
public Client[] clients;
/**
* @param parent typically use "this"
* @param port port used to transfer data
*/
public Server(PApplet parent, int port) {
this(parent, port, null);
}
/**
* @param parent typically use "this"
* @param port port used to transfer data
* @param host when multiple NICs are in use, the ip (or name) to bind from
*/
public Server(PApplet parent, int port, String host) {
this.parent = parent;
this.port = port;
try {
if (host == null) {
server = new ServerSocket(this.port);
} else {
server = new ServerSocket(this.port, 10, InetAddress.getByName(host));
}
//clients = new Vector();
clients = new Client[10];
thread = new Thread(this);
thread.start();
parent.registerMethod("dispose", this);
// reflection to check whether host sketch has a call for
// public void serverEvent(Server s, Client c);
// which is called when a new guy connects
try {
serverEventMethod =
parent.getClass().getMethod("serverEvent", Server.class, Client.class);
} catch (Exception e) {
// no such method, or an error.. which is fine, just ignore
}
} catch (IOException e) {
//e.printStackTrace();
thread = null;
throw new RuntimeException(e);
//errorMessage("<init>", e);
}
}
/**
*
* Disconnect a particular client.
*
* @webref server
* @webBrief Disconnect a particular client
* @param client the client to disconnect
*/
public void disconnect(Client client) {
client.stop();
synchronized (clientsLock) {
int index = clientIndex(client);
if (index != -1) {
removeIndex(index);
}
}
}
protected void removeIndex(int index) {
synchronized (clientsLock) {
clientCount--;
// shift down the remaining clients
for (int i = index; i < clientCount; i++) {
clients[i] = clients[i + 1];
}
// mark last empty var for garbage collection
clients[clientCount] = null;
}
}
protected void disconnectAll() {
synchronized (clientsLock) {
for (int i = 0; i < clientCount; i++) {
try {
clients[i].stop();
} catch (Exception e) {
// ignore
}
clients[i] = null;
}
clientCount = 0;
}
}
protected void addClient(Client client) {
synchronized (clientsLock) {
if (clientCount == clients.length) {
clients = (Client[]) PApplet.expand(clients);
}
clients[clientCount++] = client;
}
}
protected int clientIndex(Client client) {
synchronized (clientsLock) {
for (int i = 0; i < clientCount; i++) {
if (clients[i] == client) {
return i;
}
}
return -1;
}
}
/**
*
* Returns <b>true</b> if this server is still active and hasn't run
* into any trouble.
*
* @webref server
* @webBrief Return <b>true</b> if this server is still active
*/
public boolean active() {
return thread != null;
}
static public String ip() {
try {
return InetAddress.getLocalHost().getHostAddress();
} catch (UnknownHostException e) {
e.printStackTrace();
return null;
}
}
// the last index used for available. can't just cycle through
// the clients in order from 0 each time, because if client 0 won't
// shut up, then the rest of the clients will never be heard from.
int lastAvailable = -1;
/**
*
* Returns the next client in line with a new message.
*
* @webref server
* @webBrief Returns the next client in line with a new message
* @usage application
*/
public Client available() {
synchronized (clientsLock) {
int index = lastAvailable + 1;
if (index >= clientCount) index = 0;
for (int i = 0; i < clientCount; i++) {
int which = (index + i) % clientCount;
Client client = clients[which];
//Check for valid client
if (!client.active()){
removeIndex(which); //Remove dead client
i--; //Don't skip the next client
//If the client has data make sure lastAvailable
//doesn't end up skipping the next client
which--;
//fall through to allow data from dead clients
//to be retreived.
}
if (client.available() > 0) {
lastAvailable = which;
return client;
}
}
}
return null;
}
/**
*
* Disconnects all clients and stops the server.
*
* <h3>Advanced</h3>
* Use this to shut down the server if you finish using it while your sketch
* is still running. Otherwise, it will be automatically be shut down by the
* host PApplet using dispose(), which is identical.
* @webref server
* @webBrief Disconnects all clients and stops the server
* @usage application
*/
public void stop() {
dispose();
}
/**
* Disconnect all clients and stop the server: internal use only.
*/
public void dispose() {
thread = null;
if (clients != null) {
disconnectAll();
clientCount = 0;
clients = null;
}
try {
if (server != null) {
server.close();
server = null;
}
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void run() {
while (Thread.currentThread() == thread) {
try {
Socket socket = server.accept();
Client client = new Client(parent, socket);
synchronized (clientsLock) {
addClient(client);
if (serverEventMethod != null) {
try {
serverEventMethod.invoke(parent, this, client);
} catch (Exception e) {
System.err.println("Disabling serverEvent() for port " + port);
Throwable cause = e;
// unwrap the exception if it came from the user code
if (e instanceof InvocationTargetException && e.getCause() != null) {
cause = e.getCause();
}
cause.printStackTrace();
serverEventMethod = null;
}
}
}
} catch (SocketException e) {
//thrown when server.close() is called and server is waiting on accept
System.err.println("Server SocketException: " + e.getMessage());
thread = null;
} catch (IOException e) {
//errorMessage("run", e);
e.printStackTrace();
thread = null;
}
}
}
/**
*
* Writes a value to all the connected clients. It sends bytes out from the
* Server object.
*
* @webref server
* @webBrief Writes data to all connected clients
* @param data data to write
*/
public void write(int data) { // will also cover char
synchronized (clientsLock) {
int index = 0;
while (index < clientCount) {
if (clients[index].active()) {
clients[index].write(data);
index++;
} else {
removeIndex(index);
}
}
}
}
public void write(byte data[]) {
synchronized (clientsLock) {
int index = 0;
while (index < clientCount) {
if (clients[index].active()) {
clients[index].write(data);
index++;
} else {
removeIndex(index);
}
}
}
}
public void write(String data) {
synchronized (clientsLock) {
int index = 0;
while (index < clientCount) {
if (clients[index].active()) {
clients[index].write(data);
index++;
} else {
removeIndex(index);
}
}
}
}
}