code: void writeMessage(ModbusMessage msg, boolean useRtuOverTcp) throws ModbusIOException {
          try {
              if (logger.isDebugEnabled()) {
                  logger.debug("Sending: {}", msg.getHexMessage());
              }
              byte message[] = msg.getMessage();
  
              byteOutputStream.reset();
              if (!headless) {
                  byteOutputStream.writeShort(msg.getTransactionID());
                  byteOutputStream.writeShort(msg.getProtocolID());
                  byteOutputStream.writeShort((message != null ? message.length : 0) + 2);
              }
              byteOutputStream.writeByte(msg.getUnitID());
              byteOutputStream.writeByte(msg.getFunctionCode());
              if (message != null && message.length > 0) {
                  byteOutputStream.write(message);
              }
  
              // Add CRC for RTU over TCP
              if (useRtuOverTcp) {
                  int len = byteOutputStream.size();
                  int[] crc = ModbusUtil.calculateCRC(byteOutputStream.getBuffer(), 0, len);
                  byteOutputStream.writeByte(crc[0]);
                  byteOutputStream.writeByte(crc[1]);
              }
  
              dataOutputStream.write(byteOutputStream.toByteArray());
              dataOutputStream.flush();
              if (logger.isDebugEnabled()) {
                  logger.debug("Successfully sent: {}", ModbusUtil.toHex(byteOutputStream.toByteArray()));
              }
              // write more sophisticated exception handling
          }
          catch (SocketException ex1) {
              if (master != null && !master.isConnected()) {
                  try {
                      master.connect(useRtuOverTcp);
                  }
                  catch (Exception e) {
                      // Do nothing.
                  }
              }
              throw new ModbusIOException("I/O socket exception - failed to write - %s", ex1.getMessage());
          }
          catch (Exception ex2) {
              throw new ModbusIOException("General exception - failed to write - %s", ex2.getMessage());
          }
      }
docs: Writes a <tt>ModbusMessage</tt> to the
  output stream of this <tt>ModbusTransport</tt>.
  <p>
  
  @param msg           a <tt>ModbusMessage</tt>.
  @param useRtuOverTcp True if the RTU protocol should be used over TCP
  
  @throws ModbusIOException data cannot be
  written properly to the raw output stream of
  this <tt>ModbusTransport</tt>.