simple client/server
-
how can I transfer a file using TCP packet by packet (regardlless the packet size)? how can I transfer a file using UDP packet by packet (regardlless the packet size)? or on another mean how can I do the folloing: J.U.S.T
You need to use some other protocol - it can, if you insist, be one you design yourself - on top of TCP because TCP does not preserve message boundaries, so you need to tell the receiver how much data to expect, or look for some terminator. For example, HTTP terminates the headers with a blank line (the sequence CR-LF-CR-LF) and either uses the Content-Length header to indicate how much data is present, or closes the connection once all data has been transmitted (IIRC). FTP uses a separate connection for data transfer, the end of the data being signalled by closing the connection. UDP preserves message boundaries but is not reliable - you have no way to know whether a particular packet has arrived unless you code the receiver to send acknowledgements. You often find that you end up reinventing about 90% of TCP if you try to come up with a multi-block data-transfer scheme. You should not send more data in one message than the network can actually fit into an IP packet (the Maximum Transmission Unit), because otherwise the datagram will be fragmented, which has a massively detrimental effect on datagram loss. Say that packet loss in the route to the receiver is 5%. The chances of a datagram that fits into a single packet arriving is 95%. The chances of a datagram that must be split into two packets (fragments) arriving successfully is 95% x 95% = 90.25%, so you now get nearly 10% packet loss. The problem gets worse the more fragments you have. Unfortunately different networks have different MTU sizes. TCP has a feature called Path MTU Discovery which allows it to work out how much data it can send in one packet without causing fragmentation. This feature relies on Internet Control Message Protocol (ICMP) responses from routers when asked to process a packet too big for the network it would be sent on. These messages will not be passed on to your application by the TCP/IP stack, so you cannot reimplement this feature in your own UDP-based protocol. Stick to using UDP for single request/response pairs that will fit in a single packet, and use TCP for everything else. For file transfers I'd definitely use TCP. For more information on the protocols, see the Winsock Programmer's FAQ[^]. This is oriented more towards native, rather than managed, programming, but should still be useful. The .NET Framework contains a canned implementation of the