Readd voice server (#5374)

* Add back the voice server defaulted to disabled

* Port 098472a make voice output properly sleepy

* Cleanup some of the voice server code

* Keep track of UUID in VoiceConnection instead of username

* Collapse a few missed error logging into stack trace printing

* Add tooltip to walkie talkie when voice server is disabled

* Fix single player crash if voice server is enabled after launch before world start
This commit is contained in:
Richard Freimer authored and GitHub committed 2019-04-10 15:12:12 -04:00
1 parent a1e0688af8
commit a776879eed
16 files changed
+661 -6

No files matched your search

@@ -0,0 +1,37 @@
package mekanism.client;
import java.net.InetSocketAddress;
import mekanism.client.voice.VoiceClient;
import mekanism.common.Mekanism;
import mekanism.common.config.MekanismConfig.general;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
import net.minecraftforge.fml.common.network.FMLNetworkEvent.ClientConnectedToServerEvent;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
@SideOnly(Side.CLIENT)
public class ClientConnectionHandler {
@SubscribeEvent
public void onConnection(ClientConnectedToServerEvent event) {
if (general.voiceServerEnabled) {
if (event.isLocal()) {
// If the client is connecting to its own corresponding integrated server.
try {
MekanismClient.voiceClient = new VoiceClient("127.0.0.1");
// Will probably not work when multiple integrateds are running on one computer
} catch (Throwable e) {
Mekanism.logger.error("Unable to establish VoiceClient on local connection.", e);
}
} else {
// If the client is connecting to a foreign integrated or dedicated server.
try {
MekanismClient.voiceClient = new VoiceClient(
((InetSocketAddress) event.getManager().getRemoteAddress()).getHostString());
} catch (Throwable e) {
Mekanism.logger.error("Unable to establish VoiceClient on remote connection.", e);
}
}
}
}
}
@@ -131,6 +131,7 @@ import mekanism.common.block.states.BlockStatePlastic.PlasticBlockStateMapper;
import mekanism.common.block.states.BlockStateTransmitter.TransmitterStateMapper;
import mekanism.common.block.states.BlockStateTransmitter.TransmitterType;
import mekanism.common.config.MekanismConfig.client;
import mekanism.common.config.MekanismConfig.general;
import mekanism.common.entity.EntityBabySkeleton;
import mekanism.common.entity.EntityBalloon;
import mekanism.common.entity.EntityFlame;
@@ -1079,6 +1080,7 @@ public class ClientProxy extends CommonProxy {
* 255);
}, MekanismItems.Balloon);
MinecraftForge.EVENT_BUS.register(new ClientConnectionHandler());
MinecraftForge.EVENT_BUS.register(new ClientPlayerTracker());
MinecraftForge.EVENT_BUS.register(new ClientTickHandler());
MinecraftForge.EVENT_BUS.register(new RenderTickHandler());
@@ -1089,6 +1091,14 @@ public class ClientProxy extends CommonProxy {
HolidayManager.init();
}
@Override
public void onConfigSync(boolean fromPacket) {
super.onConfigSync(fromPacket);
if (fromPacket && general.voiceServerEnabled && MekanismClient.voiceClient != null) {
MekanismClient.voiceClient.start();
}
}
@SubscribeEvent
public void onModelBake(ModelBakeEvent event) {
IRegistry<ModelResourceLocation, IBakedModel> modelRegistry = event.getModelRegistry();
@@ -6,8 +6,10 @@ import java.util.UUID;
import mekanism.api.MekanismAPI;
import mekanism.api.MekanismAPI.BoxBlacklistEvent;
import mekanism.client.render.obj.TransmitterModel;
import mekanism.client.voice.VoiceClient;
import mekanism.common.Mekanism;
import mekanism.common.base.IModule;
import mekanism.common.config.MekanismConfig.general;
import mekanism.common.content.boiler.SynchronizedBoilerData;
import mekanism.common.network.PacketKey.KeyMessage;
import mekanism.common.security.SecurityData;
@@ -20,6 +22,7 @@ public class MekanismClient extends Mekanism {
public static Map<UUID, SecurityData> clientSecurityMap = new HashMap<>();
public static Map<UUID, String> clientUUIDMap = new HashMap<>();
public static VoiceClient voiceClient;
public static long ticksPassed = 0;
public static void updateKey(KeyBinding key, int type) {
@@ -35,6 +38,13 @@ public class MekanismClient extends Mekanism {
clientSecurityMap.clear();
clientUUIDMap.clear();
if (general.voiceServerEnabled) {
if (MekanismClient.voiceClient != null) {
MekanismClient.voiceClient.disconnect();
MekanismClient.voiceClient = null;
}
}
ClientTickHandler.tickingSet.clear();
ClientTickHandler.portableTeleports.clear();
@@ -47,18 +47,21 @@ public class MekanismKeyHandler extends MekKeyHandler {
Keyboard.KEY_M, keybindCategory);
public static KeyBinding armorModeSwitchKey = new KeyBinding("Mekanism " + LangUtils.localize("key.armorMode"),
Keyboard.KEY_G, keybindCategory);
public static KeyBinding voiceKey = new KeyBinding("Mekanism " + LangUtils.localize("key.voice"), Keyboard.KEY_U,
keybindCategory);
public static KeyBinding freeRunnerModeSwitchKey = new KeyBinding("Mekanism " + LangUtils.localize("key.feetMode"),
Keyboard.KEY_H, keybindCategory);
public static KeyBinding sneakKey = Minecraft.getMinecraft().gameSettings.keyBindSneak;
public static KeyBinding jumpKey = Minecraft.getMinecraft().gameSettings.keyBindJump;
public MekanismKeyHandler() {
super(new KeyBinding[]{modeSwitchKey, armorModeSwitchKey, freeRunnerModeSwitchKey},
new boolean[]{false, false, false});
super(new KeyBinding[]{modeSwitchKey, armorModeSwitchKey, freeRunnerModeSwitchKey, voiceKey},
new boolean[]{false, false, false, true});
ClientRegistry.registerKeyBinding(modeSwitchKey);
ClientRegistry.registerKeyBinding(armorModeSwitchKey);
ClientRegistry.registerKeyBinding(freeRunnerModeSwitchKey);
ClientRegistry.registerKeyBinding(voiceKey);
MinecraftForge.EVENT_BUS.register(this);
}
@@ -0,0 +1,98 @@
package mekanism.client.voice;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.net.ConnectException;
import java.net.Socket;
import javax.sound.sampled.AudioFormat;
import mekanism.common.Mekanism;
import mekanism.common.config.MekanismConfig.general;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
@SideOnly(Side.CLIENT)
public class VoiceClient extends Thread {
private AudioFormat format = new AudioFormat(16000F, 16, 1, true, true);
private VoiceOutput outputThread;
private VoiceInput inputThread;
private DataOutputStream output;
private DataInputStream input;
private boolean running;
private Socket socket;
private String ip;
public VoiceClient(String s) {
ip = s;
}
@Override
public void run() {
Mekanism.logger.info("VoiceServer: Starting client connection...");
try {
socket = new Socket(ip, general.VOICE_PORT);
running = true;
input = new DataInputStream(new BufferedInputStream(socket.getInputStream()));
output = new DataOutputStream(new BufferedOutputStream(socket.getOutputStream()));
(outputThread = new VoiceOutput(this)).start();
(inputThread = new VoiceInput(this)).start();
Mekanism.logger.info("VoiceServer: Successfully connected to server.");
} catch (ConnectException e) {
Mekanism.logger.error("VoiceServer: Server's VoiceServer is disabled.");
} catch (Exception e) {
Mekanism.logger.error("VoiceServer: Error while starting client connection.", e);
}
}
public void disconnect() {
Mekanism.logger.info("VoiceServer: Stopping client connection...");
try {
if (inputThread != null) {
inputThread.interrupt();
inputThread.close();
}
if (outputThread != null) {
outputThread.interrupt();
outputThread.close();
}
if (output != null) {
output.close();
}
if (input != null) {
input.close();
}
if (socket != null) {
socket.close();
}
interrupt();
running = false;
} catch (Exception e) {
Mekanism.logger.error("VoiceServer: Error while stopping client connection.", e);
}
}
public boolean isRunning() {
return running;
}
public DataOutputStream getOutputStream() {
return output;
}
public DataInputStream getInputStream() {
return input;
}
public AudioFormat getAudioFormat() {
return format;
}
}
@@ -0,0 +1,92 @@
package mekanism.client.voice;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.TargetDataLine;
import mekanism.client.MekanismKeyHandler;
import mekanism.common.Mekanism;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
@SideOnly(Side.CLIENT)
public class VoiceInput extends Thread {
private VoiceClient voiceClient;
private DataLine.Info microphone;
private TargetDataLine targetLine;
public VoiceInput(VoiceClient client) {
voiceClient = client;
microphone = new DataLine.Info(TargetDataLine.class, voiceClient.getAudioFormat(), 2200);
setDaemon(true);
setName("VoiceServer Client Input Thread");
}
@Override
public void run() {
try {
if (!AudioSystem.isLineSupported(microphone)) {
Mekanism.logger.info("No audio system available.");
return;
}
targetLine = ((TargetDataLine) AudioSystem.getLine(microphone));
targetLine.open(voiceClient.getAudioFormat(), 2200);
targetLine.start();
AudioInputStream audioInput = new AudioInputStream(targetLine);
boolean doFlush = false;
while (voiceClient.isRunning()) {
if (MekanismKeyHandler.voiceKey.isPressed()) {
targetLine.flush();
while (voiceClient.isRunning() && MekanismKeyHandler.voiceKey.isPressed()) {
try {
int availableBytes = audioInput.available();
byte[] audioData = new byte[availableBytes > 2200 ? 2200 : availableBytes];
int bytesRead = audioInput.read(audioData, 0, audioData.length);
if (bytesRead > 0) {
voiceClient.getOutputStream().writeShort(audioData.length);
voiceClient.getOutputStream().write(audioData);
}
} catch (Exception ignored) {
}
}
try {
Thread.sleep(200L);
} catch (Exception ignored) {
}
doFlush = true;
} else if (doFlush) {
try {
voiceClient.getOutputStream().flush();
} catch (Exception ignored) {
}
doFlush = false;
}
try {
Thread.sleep(20L);
} catch (Exception ignored) {
}
}
audioInput.close();
} catch (Exception e) {
Mekanism.logger.error("VoiceServer: Error while running client input thread.", e);
}
}
public void close() {
if (targetLine != null) {
targetLine.flush();
targetLine.close();
}
}
}
@@ -0,0 +1,75 @@
package mekanism.client.voice;
import java.io.EOFException;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.SourceDataLine;
import mekanism.common.Mekanism;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
@SideOnly(Side.CLIENT)
public class VoiceOutput extends Thread {
private VoiceClient voiceClient;
private DataLine.Info speaker;
private SourceDataLine sourceLine;
public VoiceOutput(VoiceClient client) {
voiceClient = client;
speaker = new DataLine.Info(SourceDataLine.class, voiceClient.getAudioFormat(), 2200);
setDaemon(true);
setName("VoiceServer Client Output Thread");
}
@Override
public void run() {
try {
sourceLine = ((SourceDataLine) AudioSystem.getLine(speaker));
sourceLine.open(voiceClient.getAudioFormat(), 2200);
sourceLine.start();
byte[] audioData = new byte[4096]; //less allocation/gc (if done outside the loop)
int byteCount;
int length;
while (voiceClient.isRunning()) {
try {
if (voiceClient.getInputStream().available() > 0) {
//Why would we only read signed shorts? negative amount of waiting data doesn't make sense anyway :D
byteCount = voiceClient.getInputStream().readUnsignedShort();
while (byteCount > 0 && voiceClient.isRunning()) {
length = audioData.length;
if (length > byteCount) {
length = byteCount;
}
//That one returns the actual read amount of data (we can begin transferring even if input
// is waiting/incomplete)
length = voiceClient.getInputStream().read(audioData, 0, length);
if (length < 0) {
throw new EOFException();
}
sourceLine.write(audioData, 0, length);
byteCount -= length;
}
} else {
Thread.sleep(20);
}
} catch (EOFException eof) {
Mekanism.logger.error("VoiceServer: Unexpected input EOF Exception occurred.");
break; // voiceClient.input will continue throwing EOFs -> no need to go on checking
} catch (InterruptedException e) {
break;
} catch (Exception e) {
Mekanism.logger.error(e);
}
}
} catch (Exception e) {
Mekanism.logger.error("VoiceServer: Error while running client output thread.", e);
}
}
public void close() {
sourceLine.flush();
sourceLine.close();
}
}
+12 -4
View File
@@ -57,7 +57,6 @@ import mekanism.common.inventory.container.robit.ContainerRobitMain;
import mekanism.common.inventory.container.robit.ContainerRobitRepair;
import mekanism.common.inventory.container.robit.ContainerRobitSmelting;
import mekanism.common.item.ItemPortableTeleporter;
import mekanism.common.multiblock.UpdateProtocol.NodeChecker;
import mekanism.common.network.PacketPortableTeleporter.PortableTeleporterMessage;
import mekanism.common.tile.TileEntityChanceMachine;
import mekanism.common.tile.TileEntityChemicalCrystallizer;
@@ -80,7 +79,6 @@ import mekanism.common.tile.TileEntityInductionCasing;
import mekanism.common.tile.TileEntityLaserAmplifier;
import mekanism.common.tile.TileEntityLaserTractorBeam;
import mekanism.common.tile.TileEntityMetallurgicInfuser;
import mekanism.common.tile.TileEntityMultiblock;
import mekanism.common.tile.TileEntityOredictionificator;
import mekanism.common.tile.TileEntityPRC;
import mekanism.common.tile.TileEntityQuantumEntangloporter;
@@ -97,6 +95,7 @@ import mekanism.common.tile.prefab.TileEntityDoubleElectricMachine;
import mekanism.common.tile.prefab.TileEntityElectricMachine;
import mekanism.common.util.UnitDisplayUtils.EnergyType;
import mekanism.common.util.UnitDisplayUtils.TempType;
import mekanism.common.voice.VoiceServerManager;
import net.minecraft.block.Block;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EntityPlayerMP;
@@ -173,6 +172,8 @@ public class CommonProxy implements IGuiProvider {
.getBoolean();
general.dynamicTankEasterEgg = Mekanism.configuration
.get(Configuration.CATEGORY_GENERAL, "DynamicTankEasterEgg", false, "Audible sparkles.").getBoolean();
general.voiceServerEnabled = Mekanism.configuration
.get(Configuration.CATEGORY_GENERAL, "WalkieTalkieServerEnabled", false).getBoolean();
general.cardboardSpawners = Mekanism.configuration
.get(Configuration.CATEGORY_GENERAL, "AllowSpawnerBoxPickup", true,
"Allows vanilla spawners to be moved with a Cardboard Box.").getBoolean();
@@ -253,6 +254,8 @@ public class CommonProxy implements IGuiProvider {
general.DISASSEMBLER_USAGE = Mekanism.configuration
.get(Configuration.CATEGORY_GENERAL, "DisassemblerEnergyUsage", 10,
"Base Energy (Joules) usage of the Atomic Disassembler.").getInt();
general.VOICE_PORT = Mekanism.configuration
.get(Configuration.CATEGORY_GENERAL, "VoicePort", 36123, null, 1, 65535).getInt();
//If this is less than 1, upgrades make machines worse. If less than 0, I don't even know.
general.maxUpgradeMultiplier = Mekanism.configuration
.get(Configuration.CATEGORY_GENERAL, "UpgradeModifier", 10,
@@ -514,13 +517,15 @@ public class CommonProxy implements IGuiProvider {
/**
* Does the multiblock creation animation, starting from the rendering block.
*/
public void doMultiblockSparkle(TileEntity tileEntity, BlockPos corner1, BlockPos corner2, INodeChecker checker) {}
public void doMultiblockSparkle(TileEntity tileEntity, BlockPos corner1, BlockPos corner2, INodeChecker checker) {
}
/**
* Does the multiblock creation animation, starting from the rendering block.
*/
public void doMultiblockSparkle(TileEntity tileEntity, BlockPos renderLoc, int length, int width, int height,
INodeChecker checker) {}
INodeChecker checker) {
}
@Override
public Object getClientGui(int ID, EntityPlayer player, World world, BlockPos pos) {
@@ -723,6 +728,9 @@ public class CommonProxy implements IGuiProvider {
BlockStateMachine.MachineType.updateAllUsages();
if (general.voiceServerEnabled && Mekanism.voiceManager == null) {
Mekanism.voiceManager = new VoiceServerManager();
}
if (fromPacket) {
Mekanism.logger.info("Received config from server.");
}
@@ -137,6 +137,7 @@ import mekanism.common.transmitters.grid.EnergyNetwork.EnergyTransferEvent;
import mekanism.common.transmitters.grid.FluidNetwork.FluidTransferEvent;
import mekanism.common.transmitters.grid.GasNetwork.GasTransferEvent;
import mekanism.common.util.MekanismUtils;
import mekanism.common.voice.VoiceServerManager;
import mekanism.common.world.GenHandler;
import net.minecraft.block.Block;
import net.minecraft.entity.EnumCreatureType;
@@ -267,6 +268,10 @@ public class Mekanism {
* changes.
*/
public static int baseWorldGenVersion = 0;
/**
* The VoiceServer manager for walkie talkies
*/
public static VoiceServerManager voiceManager;
/**
* The GameProfile used by the dummy Mekanism player
*/
@@ -864,11 +869,18 @@ public class Mekanism {
@EventHandler
public void serverStarting(FMLServerStartingEvent event) {
if (general.voiceServerEnabled) {
voiceManager.start();
}
CommandMek.register(event);
}
@EventHandler
public void serverStopping(FMLServerStoppingEvent event) {
if (general.voiceServerEnabled) {
voiceManager.stop();
}
//Clear all cache data
playerState.clear();
activeVibrators.clear();
@@ -979,6 +991,11 @@ public class Mekanism {
//Register this module's GUI handler in the simple packet protocol
PacketSimpleGui.handlers.add(0, proxy);
//Set up VoiceServerManager
if (general.voiceServerEnabled) {
voiceManager = new VoiceServerManager();
}
//Register with TransmitterNetworkRegistry
TransmitterNetworkRegistry.initiate();
@@ -13,6 +13,7 @@ public class MekanismConfig {
public static boolean controlCircuitOreDict = true;
public static boolean logPackets = false;
public static boolean dynamicTankEasterEgg = false;
public static boolean voiceServerEnabled = false;
public static boolean cardboardSpawners = true;
public static boolean enableWorldRegeneration = true;
public static boolean spawnBabySkeletons = true;
@@ -27,6 +28,7 @@ public class MekanismConfig {
public static int saltMaxVeinSize = 6;
public static int obsidianTNTDelay = 100;
public static int UPDATE_DELAY = 10;
public static int VOICE_PORT = 36123;
public static int maxUpgradeMultiplier = 10;
public static int userWorldGenVersion = 0;
public static double ENERGY_PER_REDSTONE = 10000;
@@ -7,6 +7,7 @@ import java.util.Map;
import javax.annotation.Nonnull;
import mekanism.api.EnumColor;
import mekanism.common.base.IItemNetwork;
import mekanism.common.config.MekanismConfig.general;
import mekanism.common.util.ItemDataUtils;
import mekanism.common.util.LangUtils;
import net.minecraft.client.renderer.block.model.ModelResourceLocation;
@@ -48,6 +49,9 @@ public class ItemWalkieTalkie extends ItemMekanism implements IItemNetwork {
.localize("gui." + (getOn(itemstack) ? "on" : "off")));
list.add(EnumColor.DARK_AQUA + LangUtils.localize("tooltip.channel") + ": " + EnumColor.GREY + getChannel(
itemstack));
if (!general.voiceServerEnabled) {
list.add(EnumColor.DARK_RED + LangUtils.localize("tooltip.walkie_disabled"));
}
}
@Nonnull
@@ -31,6 +31,7 @@ public class PacketConfigSync implements IMessageHandler<ConfigSyncMessage, IMes
dataStream.writeBoolean(general.controlCircuitOreDict);
dataStream.writeBoolean(general.logPackets);
dataStream.writeBoolean(general.dynamicTankEasterEgg);
dataStream.writeBoolean(general.voiceServerEnabled);
dataStream.writeBoolean(general.cardboardSpawners);
dataStream.writeBoolean(general.spawnBabySkeletons);
dataStream.writeInt(general.obsidianTNTDelay);
@@ -48,6 +49,7 @@ public class PacketConfigSync implements IMessageHandler<ConfigSyncMessage, IMes
dataStream.writeInt(general.ETHENE_BURN_TIME);
dataStream.writeDouble(general.ENERGY_PER_REDSTONE);
dataStream.writeDouble(general.DISASSEMBLER_USAGE);
dataStream.writeInt(general.VOICE_PORT);
dataStream.writeInt(general.maxUpgradeMultiplier);
dataStream.writeInt(general.energyUnit.ordinal());
dataStream.writeDouble(general.minerSilkMultiplier);
@@ -124,6 +126,7 @@ public class PacketConfigSync implements IMessageHandler<ConfigSyncMessage, IMes
general.controlCircuitOreDict = dataStream.readBoolean();
general.logPackets = dataStream.readBoolean();
general.dynamicTankEasterEgg = dataStream.readBoolean();
general.voiceServerEnabled = dataStream.readBoolean();
general.cardboardSpawners = dataStream.readBoolean();
general.spawnBabySkeletons = dataStream.readBoolean();
general.obsidianTNTDelay = dataStream.readInt();
@@ -141,6 +144,7 @@ public class PacketConfigSync implements IMessageHandler<ConfigSyncMessage, IMes
general.ETHENE_BURN_TIME = dataStream.readInt();
general.ENERGY_PER_REDSTONE = dataStream.readDouble();
general.DISASSEMBLER_USAGE = dataStream.readDouble();
general.VOICE_PORT = dataStream.readInt();
general.maxUpgradeMultiplier = dataStream.readInt();
general.energyUnit = EnergyType.values()[dataStream.readInt()];
general.minerSilkMultiplier = dataStream.readDouble();
@@ -0,0 +1,163 @@
package mekanism.common.voice;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.UUID;
import mekanism.common.Mekanism;
import mekanism.common.item.ItemWalkieTalkie;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.item.ItemStack;
import net.minecraft.server.MinecraftServer;
import net.minecraftforge.fml.common.FMLCommonHandler;
public class VoiceConnection extends Thread {
private MinecraftServer server = FMLCommonHandler.instance().getMinecraftServerInstance();
private DataOutputStream output;
private DataInputStream input;
private boolean open = true;
private Socket socket;
private UUID uuid;
public VoiceConnection(Socket s) {
socket = s;
}
@Override
public void run() {
try {
input = new DataInputStream(new BufferedInputStream(socket.getInputStream()));
output = new DataOutputStream(new BufferedOutputStream(socket.getOutputStream()));
synchronized (Mekanism.voiceManager) {
int retryCount = 0;
while (uuid == null && retryCount <= 100) {
try {
List<EntityPlayerMP> l = Collections
.synchronizedList(new ArrayList<>(server.getPlayerList().getPlayers()));
for (EntityPlayerMP playerMP : l) {
String playerIP = playerMP.getPlayerIP();
if (!server.isDedicatedServer() && playerIP.equals("local") && !Mekanism.voiceManager
.isFoundLocal()) {
Mekanism.voiceManager.setFoundLocal(true);
uuid = playerMP.getUniqueID();
break;
} else if (playerIP.equals(socket.getInetAddress().getHostAddress())) {
uuid = playerMP.getUniqueID();
break;
}
}
retryCount++;
Thread.sleep(50);
} catch (Exception ignored) {
}
}
if (uuid == null) {
Mekanism.logger.error("VoiceServer: Unable to trace connection's IP address.");
kill();
return;
} else {
Mekanism.logger.info("VoiceServer: Traced IP in " + retryCount + " attempts.");
}
}
} catch (Exception e) {
Mekanism.logger.error("VoiceServer: Error while starting server-based connection.", e);
open = false;
}
// Main client listen thread
new Thread(() -> {
while (open) {
try {
short byteCount = VoiceConnection.this.input.readShort();
byte[] audioData = new byte[byteCount];
VoiceConnection.this.input.readFully(audioData);
if (byteCount > 0) {
Mekanism.voiceManager.sendToPlayers(byteCount, audioData, VoiceConnection.this);
}
} catch (Exception e) {
open = false;
}
}
if (!open) {
kill();
}
}).start();
}
private void kill() {
try {
if (input != null) {
input.close();
}
if (output != null) {
output.close();
}
if (socket != null) {
socket.close();
}
Mekanism.voiceManager.removeConnection(this);
} catch (Exception e) {
Mekanism.logger.error("VoiceServer: Error while stopping server-based connection.", e);
}
}
public void sendToPlayer(short byteCount, byte[] audioData, VoiceConnection connection) {
if (!open) {
kill();
}
try {
output.writeShort(byteCount);
output.write(audioData);
output.flush();
} catch (Exception e) {
Mekanism.logger.error("VoiceServer: Error while sending data to player.", e);
}
}
public boolean canListen(int channel) {
return getPlayer().inventory.mainInventory.stream().anyMatch(itemStack -> canListen(channel, itemStack))
|| getPlayer().inventory.offHandInventory.stream().anyMatch(itemStack -> canListen(channel, itemStack));
}
private boolean canListen(int channel, ItemStack itemStack) {
if (!itemStack.isEmpty() && itemStack.getItem() instanceof ItemWalkieTalkie) {
ItemWalkieTalkie walkieTalkie = (ItemWalkieTalkie) itemStack.getItem();
return walkieTalkie.getOn(itemStack) && walkieTalkie.getChannel(itemStack) == channel;
}
return false;
}
public int getCurrentChannel() {
ItemStack itemStack = getPlayer().inventory.getCurrentItem();
if (!itemStack.isEmpty() && itemStack.getItem() instanceof ItemWalkieTalkie) {
ItemWalkieTalkie walkieTalkie = (ItemWalkieTalkie) itemStack.getItem();
if (walkieTalkie.getOn(itemStack)) {
return walkieTalkie.getChannel(itemStack);
}
}
return 0;
}
public EntityPlayerMP getPlayer() {
return server.getPlayerList().getPlayerByUUID(uuid);
}
}
@@ -0,0 +1,107 @@
package mekanism.common.voice;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.util.HashSet;
import java.util.Set;
import mekanism.common.Mekanism;
import mekanism.common.config.MekanismConfig.general;
public class VoiceServerManager {
private Set<VoiceConnection> connections = new HashSet<>();
private ServerSocket serverSocket;
private Thread listenThread;
private boolean foundLocal = false;
private boolean running;
public void start() {
Mekanism.logger.info("VoiceServer: Starting up server...");
try {
running = true;
serverSocket = new ServerSocket(general.VOICE_PORT);
(listenThread = new ListenThread()).start();
} catch (Exception ignored) {
}
}
public void stop() {
try {
Mekanism.logger.info("VoiceServer: Shutting down server...");
try {
listenThread.interrupt();
} catch (Exception ignored) {
}
foundLocal = false;
try {
serverSocket.close();
serverSocket = null;
} catch (Exception ignored) {
}
} catch (Exception e) {
Mekanism.logger.error("VoiceServer: Error while shutting down server.", e);
}
running = false;
}
public void removeConnection(VoiceConnection connection) {
connections.remove(connection);
}
public boolean isFoundLocal() {
return foundLocal;
}
public void setFoundLocal(boolean found) {
foundLocal = found;
}
public void sendToPlayers(short byteCount, byte[] audioData, VoiceConnection connection) {
if (connection.getPlayer() == null) {
return;
}
int channel = connection.getCurrentChannel();
if (channel == 0) {
return;
}
for (VoiceConnection iterConn : connections) {
if (iterConn.getPlayer() != null && iterConn != connection && iterConn.canListen(channel)) {
iterConn.sendToPlayer(byteCount, audioData, connection);
}
}
}
private class ListenThread extends Thread {
private ListenThread() {
setDaemon(true);
setName("VoiceServer Listen Thread");
}
@Override
public void run() {
while (running) {
try {
Socket s = serverSocket.accept();
VoiceConnection connection = new VoiceConnection(s);
connection.start();
connections.add(connection);
Mekanism.logger.info("VoiceServer: Accepted new connection.");
} catch (SocketException | NullPointerException ignored) {
} catch (Exception e) {
Mekanism.logger.error("VoiceServer: Error while accepting connection.", e);
}
}
}
}
}