91 lines
2.0 KiB
Java
91 lines
2.0 KiB
Java
package ee.lunasqu.redstoneoutput;
|
|
|
|
import java.io.BufferedReader;
|
|
import java.io.BufferedWriter;
|
|
import java.io.IOException;
|
|
import java.io.InputStreamReader;
|
|
import java.io.OutputStreamWriter;
|
|
import java.net.Socket;
|
|
|
|
import org.bukkit.Bukkit;
|
|
import org.bukkit.scheduler.BukkitRunnable;
|
|
|
|
import ee.lunasqu.redstoneoutput.events.ConnectionEstablishedEvent;
|
|
import ee.lunasqu.redstoneoutput.events.DisconnectedEvent;
|
|
|
|
public class Connection extends BukkitRunnable {
|
|
private Socket socket;
|
|
private BufferedWriter writer;
|
|
private BufferedReader reader;
|
|
|
|
private boolean alive;
|
|
|
|
public Connection(String addr, int port) {
|
|
try {
|
|
socket = new Socket(addr, port);
|
|
writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
|
|
reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
|
|
} catch (IOException e) {
|
|
e.printStackTrace();
|
|
Bukkit.getPluginManager().callEvent(new DisconnectedEvent());
|
|
return;
|
|
}
|
|
// Successful connection
|
|
Bukkit.getPluginManager().callEvent(new ConnectionEstablishedEvent());
|
|
alive = true;
|
|
}
|
|
|
|
public boolean sendStateChange (int power, String key, String value) {
|
|
if (!alive) return false;
|
|
try {
|
|
writer.write(power + ":" + key + ":" + value + "\r\n");
|
|
writer.flush();
|
|
} catch (IOException e) {
|
|
e.printStackTrace();
|
|
return false;
|
|
}
|
|
return true;
|
|
}
|
|
|
|
public void die () {
|
|
this.alive = false;
|
|
if (!socket.isClosed()) {
|
|
try {
|
|
socket.close();
|
|
} catch (IOException e) {
|
|
e.printStackTrace();
|
|
}
|
|
}
|
|
}
|
|
|
|
public boolean isAlive() {
|
|
return this.alive;
|
|
}
|
|
|
|
@Override
|
|
public void run() {
|
|
if (!this.alive) {
|
|
if (!this.isCancelled()) this.cancel();
|
|
return;
|
|
}
|
|
|
|
try {
|
|
String line;
|
|
while ((line = reader.readLine()) != null) {
|
|
line = line.trim();
|
|
|
|
if (!alive) break;
|
|
}
|
|
alive = false;
|
|
if (!socket.isClosed()) {
|
|
socket.close();
|
|
}
|
|
} catch (Exception e) {
|
|
e.printStackTrace();
|
|
}
|
|
Bukkit.getPluginManager().callEvent(new DisconnectedEvent());
|
|
this.cancel();
|
|
}
|
|
|
|
}
|