Write partially filled buffer to file.

After terminating the write thread, write all encoded bytes to file so that all
Google protocol buffer messages are complete and decoding works properly.
Fix partial buffer write.

Change which bytes are written when writing a partially filled buffer
to file. This is due to changes in buffer writes in commit
06592ced13068be54b8d5472fc7f8c323bbbb03f.