Trying to make a TCP server, client connects and disconnects immediately

Andre Kostur via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Thu Feb 5 22:19:41 PST 2015


On 2015-02-05, 8:17 PM, Gan wrote:
> On Friday, 6 February 2015 at 01:36:17 UTC, Mike Parker wrote:
>> On 2/6/2015 9:50 AM, Gan wrote:
>>> On Friday, 6 February 2015 at 00:35:12 UTC, Adam D. Ruppe wrote:
>>>> On Friday, 6 February 2015 at 00:31:37 UTC, Gan wrote:
>>>>> Or am I misunderstanding the receive function? Does it send whole
>>>>> messages or just message chunks?
>>>>
>>>> It sends as much as it can when you call it. So if there's only 12
>>>> bytes available when you send it with a 4096 buffer, it will fill the
>>>> first twelve bytes (and return 12) so you can slice it buffer[0 ..
>>>> returnedValue] to get the data.
>>>>
>>>> If there's more available than the buffer will hold, that data will be
>>>> held on to until next time you call receive. If 5000 bytes come off
>>>> the network, it will return 4096 the first time, then next time
>>>> through the loop, it will return the remaining 904.
>>>
>>> How can you distinguish between different packets that get sent? Won't
>>> they all be merged to a giant blob of data?
>>
>> You need to give each of your packets a header. At a minimum you'll
>> want a message ID and message length. When a message comes in, you use
>> the length field to determine where one packet ends and the next one
>> begins.
>
> Oh sweet. Though if one message length is off by even 1 byte, then all
> future messages get corrupted?

Yep.  You're using a reliable stream-based protocol.  If you want 
discrete messages, you can use UDP.  Though it is an unreliable 
packet-oriented protocol.  Don't foul up your message lengths....


More information about the Digitalmars-d-learn mailing list