Changed MemoryStream to have separate capacity and length.
Fixed some socket issues.