@Override
	public ByteBuffer encodeMessage(final Message msg) {
		if (msg instanceof BinaryMessage) {
			ByteBuffer buf = ((BinaryMessage) msg).codeMessage();

			byte[] name = null;

			try {
				name = msg.getClass().getCanonicalName().getBytes("UTF-8");
			} catch (UnsupportedEncodingException e) {
				// never called
				name = msg.getClass().getCanonicalName().getBytes();
			}

			ByteBuffer buffer = ByteBuffer.allocate(1 + 2 + name.length + buf.remaining());

			buffer.put(BINARY_MESSAGE_PREFIX);

			buffer.putShort((short) name.length);

			buffer.put(name);

			buffer.put(buf);

			buffer.rewind();

			return buffer;
		}


		try (ByteArrayOutputStream baos = new ByteArrayOutputStream();
				ObjectOutputStream oos = new ObjectOutputStream(baos)) {

			oos.writeObject(msg);

			oos.flush();

			byte[] bytes = baos.toByteArray();

			ByteBuffer buf = ByteBuffer.allocate(bytes.length);

			buf.put(bytes);

			buf.rewind();

			return buf;

		} catch (IOException e) {
			e.printStackTrace();
		}

		return null;
	}