Fixed several bugs in handling tcp messages.