Server and Client on one instance of a game

What do you mean by “it wouldn’t run on older versions”?

That approach where you send the server a string like ‘shoot’ is pretty OK, until you start having problems with either a) performance, b) string lengths.
If I were you, I’d probably just send the server a byte signifying a player just shot. I’d do this, because bytes have a constant size (1 byte), and I don’t have to worry about lengths. If I have to pass some arguments with my bytes, I send that argument to the server in bytes aswell, eg. an int = 4 bytes, and then the server would receive those based on the first one of the sequence. Creating the data to send could be done with the java.nio.ByteBuffer. ByteBuffer has functions to deal with converting bytes to arrays, you can use it like so:

// we allocate 5 bytes, because our instruction is (byte, int) for (command, someIntegerArgument), adding the byte numbers of byte (1) and int (4) gives us 5
// then we put a byte of value 2, and an int of value 32
// you can read more about the ByteBuffer here:
// https://docs.oracle.com/javase/7/docs/api/java/nio/ByteBuffer.html
ByteBuffer.allocate(5).put(2).putInt(32).array();

This will create an array with a byte 2 and your int converted to bytes. Remember that:

  • byte = 1 byte (duh) (8-bit)
  • short = 2 bytes (16-bit)
  • char = 2 bytes (16-bit)
  • int = 4 bytes (32-bit)
  • float = 4 bytes (32-bit)
  • long = 8 bytes (64-bit)
  • double = 8 bytes (64-bit)
    Good luck!
1 Like