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:
|
package control;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.List;
import org.json.JSONObject;
/**
* SenderThread f�r Serverkommunikation, Grundstruktur zum erstellen bzw.
* schicken von JSON-Pakete
*
*/
//ToDo: Als Timeline l�sen
public class SenderThread extends Thread {
private InetAddress server;
private DatagramSocket socket;
private boolean running = true;
private boolean playing = false;
private JSONObject send;
private List<JSONObject> toSend = new ArrayList<JSONObject>();
private int port;
/**
* Adresse/Port/Socket wird bei erstellen angegeben
* @param address
* @param port
* @throws SocketException
*/
public SenderThread(InetAddress address, int port) throws SocketException {
this.server = address;
this.port = port;
this.socket = new DatagramSocket();
this.socket.connect(server, port);
this.setDaemon(true);
System.out.println("SenderThread erstellt");
}
/**
* FÜgt ein JSON-Objekt in die Sendeliste hinzu + Aufwecken der Threads
* @param send
*/
public synchronized void addJSON(JSONObject send)
{
toSend.add(send);
notifyAll();
}
/**
* Ausschalten von run()
*/
public void end() {
running = false;
}
public DatagramSocket getSocket() {
return this.socket;
}
/**
* Sendet alle JSON-Pakete nacheinander und wartet falls es keins gibt
*/
@Override
public synchronized void run() {
try {
//BufferedReader userInput = new BufferedReader(new InputStreamReader(System.in));
while (running) {
//Update(); //Sollte ausgelagert werden
//System.out.println("Anzahl Pakete: "+toSend.size());
while(toSend.isEmpty())
{
wait();
}
SendJSON(toSend.get(0));
toSend.remove(0);
Thread.yield();
//Auch auslagern
}
}
catch (IOException | InterruptedException ex) {
System.err.println(ex);
}
}
/**
* Öffnet Verbindung zum senden
* @param obj
* @throws IOException
*/
public void SendJSON(JSONObject obj) throws IOException
{
//System.out.println("Send: "+ obj);
byte[] data = obj.toString().getBytes();
DatagramPacket output = new DatagramPacket(data, data.length, server, port);
socket.send(output);
}
|