UDP vs TCP in local network application with application-level ack system - tcp

i have a question about the trasport layer of the iso/osi network stack.
It's common to think that TCP is reliable but slow and UDP is fast but not reliable.
In several network applications, it is mandatory to implement an application-level ACK system also with TCP transport protocol in order to manage link interruptions and so on.
Assuming that the application scenario is this: local (small) network, typical small packet size (max 512 bytes), application-level ack system implementation. Why not use the protocol UDP as transport protocol in order to exploit its features such as speed, low latency and broadcast communication?
Thanks to all.

If you don't care about the Delivery (failure or successful delivery) of your message than UDP will be always a best choice.. But if you want to be sure whether the message is delivered or failed than think about other protocols rather than UDP.

In a small LAN it shouldnt be a big problem to use UDP, when the transferd Data isnt too "important" (which means if a packet is lost its no problem). More informations about the scenario are nessesary, if you use UDP you have to implement functions that check if you received all the information of the sender manually.
if you need the speed and if some lost packets are no problem (Voice Chat for instance) then use UDP.

Related

Advantages of UDP over TCP?

TCP has a greater computation overhead to ensure reliable delivery of packets. But, since modern networks are fast, is there any scenario in which performance of UDP outweighs the reliability of TCP?
Is there any other particular advantage of UDP over TCP?
I can see two cases, where UDP would have an upper hand over TCP.
First, one of the attractive features of UDP is that since it does not need to retransmit lost packets nor does it do any connection setup, sending data incurs less delay. This lower delay makes UDP an appealing choice for delay-sensitive applications like audio and video.
Second, multicast applications are built on top of UDP since they have to do point to multipoint. Using TCP for multicast applications would be hard since now the sender would have to keep track of retransmissions/sending rate for multiple receivers.
It depends on your usage. If your application is time sensitive, like Voice over IP, then you don't care about missing packets. What you care about is the delay in that case.
You should have a look at this answer: What are examples of TCP and UDP in real life?
You could also look at the Wikipedia related section: http://en.wikipedia.org/wiki/User_Datagram_Protocol#Comparison_of_UDP_and_TCP
Applications that require constant data flow, bulk data and which require fastness than reliability uses UDP over TCP.
udp provides better application level control over what data is sent....since the data is packaged in a udp segment and immediately passed over to the network layer......hence no-frills segment delivery service is observed.
There is no need for connection establishment hence no delay(unlike tcp...which requires handshaking before the actual data transfer)
There is no need to maintain connection state in the end systems(ie no need for send and receive buffers,congestion control parameters and sequence and acknowledgement number parameters)..hence more active clients could be supported
Small packet header overhead for udp(only 8 bytes) where as tcp has 20 bytes of header
Facebook uses UDP connections instead of TCP/IP to connect to theirs Memcached Servers
There are couple of differences of UDP over TCP.
First, TCP is connection-based whereas UDP is connectionless.
Connection-based: Make sure that all messages will arrive and arrive in the correct order.
Connectionless: It does not guarantee order or completeness.
Second, Here is why UDP is faster over TCP:
UDP does not require ACK message back
UDP has no flow control
No duplication verification at the receiving end
Shorter header

Can TCP be implemented via UDP?

I had a strange idea. I heard of software which from my understanding uses UDP to transfer files decreasing the overhead found in TCP packets.
If my app requires TCP and my LAN has software set up to communicate with another datacenter on the other side of the coast with software setup on their end. Would it be possible to send the actual data via UDP but than simulating TCP on both ends?
Does anyone have any ideas or information about such projects?
If you're asking if you can use UDP as a Layer 2, then the answer is yes, sort of. There are various protocols that allow you to create a tunnel to another network using a UDP transport, such as L2TP and even IPsec (with NAT traversal). You could also do it at the application layer.
If you're asking if TCP can be implemented in UDP, the answer is no. First, TCP packets and UDP packets have an incompatible format. Second, TCP and UDP have different protocol numbers (seen in the IP header) which means that TCP traffic destined for a UDP port would not be passed to the correct upper-layer protocol.
Both TCP and UDP are built on top of the IP, but the TCP uses different packet structure and at the layer-2 it is not possible to mimic the TCP using UDP packets.
Of course, if you have the control on both the source and destination, then it is possible to create a reliable UDP tunnel for the TCP packets. This would require some internal information (packet number, ack/nack flags) in the body of the UDP packet.
There is an interesting project http://udt.sourceforge.net/
It is a broadcast-capable reliable file transfer mechanism built on top the UDP.
PseudoTCP is a protocol which implements TCP algorithms on top of the UDP. It was introduced since the NAT traversal for TCP is much more complicated than UDP. But some P2P applications do need a reliable data transfer among nodes.
So far as I know, there are two PseudoTCP variations: Libjingle and Libnice.Libjingle is an open source library from google which was initially for gtalk. You could take a look at file sharing example from libjingle: https://developers.google.com/talk/libjingle/file_share. Recently, Chrome desktop also use PseudoTCP implementation from libjingle for reliable connections.
Yes, you can develop a protocol on UDP that simulates TCP. However, if you simulated TCP fully, it would technically have more overhead. Because TCP is implement as the packet and your simulated TCP is implemented in the body of the packet.
If you only need one or two features of TCP (such as basic ordering), then implementing it in UDP is useful.
Halo uses 2-3 (IIRC) UDP protocols that simulate different features of TCP, then full fledged TCP for initializing game-states. I Shot You First Networking, GDC publication
For example, in one case, they send 3 duplicate UDP packets to overcome packet loss.
If you control the software on both ends, and it is cost-effective to build your own protocol, then UDP can be versatile.
One way to do it now on Linux-3.18+ is to use Foo over UDP (FOU) which implements Generic UDP Encapsulation (GUE). Here's a good introduction to FOU, and the man page for ip-fou.
Or if you want an [open source] UDP based file transfer system there are things like UDT, UFTP, Tsunami-UDP, and even Google's QUIC (Now deprecated in favour of IETF QUIC).
Update: The QUIC protocol now has been standardised by the IETF which provides for secure reliable and unreliable transport over UDP as an alternative to TCP. There's a wide range of QUIC implementations available. There is also a growing set of protocol mappings on to QUIC such as HTTP/3, DNS over QUIC, etc
If my app requires TCP and my LAN has software setup to communicate
with another datacenter on the other side of the coast with software
setup on their end. Would it be possible to send the actual data via
UDP but than simulating TCP on both ends?
No. A UDP socket is in a different namespace from a TCP socket. You will be unable to write UDP at one end and send or receive TCP at the other end. TCP and UDP are peer protocols; both exist at the layer above IP. You can't use one to spoof the other.
Hmm, I believe so. You'd need to use a proxy at both ends, but it should be possible.
The biggest problem you are going to run into is that UDP is designed with the idea that you don't care if some of the packets don't ever make it to the other end.
Here's a link with some more info:
http://www.cyberciti.biz/faq/key-differences-between-tcp-and-udp-protocols/
IMHO, it's not a good idea to transmit files via UDP.
TCP's problems are in its algorithms, not its headers.
You certainly could implement the TCP algorithms on top of UDP. That would effectively be the same as tunneling TCP datagrams inside of UDP datagrams. But all this accomplishes is to add a few more bytes of overhead to each packet, and require another endpoint to unwrap the packets.
UDP itself is just thin shim on top of IP: its a convenient way to access IP packet switched networking without having to dive into kernels or receive special handling from routers. The main reason to implement reliable transport on top of UDP is to get away from TCP algorithms in favor of something more efficient. FileCatalyst was mentioned above as one company which does this, and my own company Data Expedition, Inc. does so as well.
So you could implement TCP algorithms on top of UDP, but you wouldn't want to.
You can simulate something like a connection over UDP, and you as well can add reliability checks and ordering and retransmission and so on. - but then, it still isn't TCP, it just acts the way.
Of course, one of the ends can be a kind of "hub" or "proxy" which does an adaption. Then you don't have a 2-end solution, but in fact a 4 end solution - one pair with "real" TCP and the other with the "self-knitted" "TCP" - which you put together with an appropriately crafted program.

High Frequency Trading - TCP > UDP?

I was told that for a High Frequency Trading (HFT) system that requires low-latency, TCP is used over UDP. I was told that with TCP you can make point to point connections, whereas you cannot with UDP, however from my understanding you can send UDP packets to specific IP/port.
There are several arguments used in this article as to why UDP > TCP for gaming but I can see relevance for HFT.
Why would TCP be a better protocol to use for HFT?
(Admins: My previous post of this question was silently removed with no explanation. If I am violating terms of use please alert me of this instead of silently removing the question)
UDP is superior to TCP if you don't need some of the features TCP provides. Every feature has a cost, and so if you don't need features, you are paying that cost for no reason.
In an HFT application, you need pretty much every feature TCP requires. So if you picked UDP, you'd have to implement those features yourself. That means you'd have to implement connection establishment, connection teardown, retransmissions, transmit pacing, windows, and so on.
If there was a way to do all those things that was better than the way TCP was doing it, TCP would be doing it that way. You'd have one hand tied behind your back because TCP is heavily optimized by some of the best minds on the planet and implemented in/with the kernel.
There's no reasons to expect a stream of data over an already-established TCP connection would be slower than the same data over UDP, plus you get checksumming, retries, and all the other TCP goodness. UDP mainly wins in cases where you can afford to discard the reliability or where the overhead of many TCP handshakes would be too expensive, such as with common DNS queries.
TCP is faster for when using a few connections, the important difference is that modern NICs perform significant amounts of acceleration on TCP and not really that much for UDP. This means there is more overhead to process each UDP packet and as such they cannot compete unless you need to send to multiple recipients simultaneously.
However the UDP multicast route still suffers the same problems as unicast UDP per datagram overheads. Therefore many HFT systems use hardware accelerated systems that can multiplex the streams across many NICs via TCP, example Solace.
These days though you want to completely bypass the kernel with say a userspace IP stack such as by Solarflare or Mellanox, or even skip both the kernel and IP stack with RDMA.
Quite simply, if you need connection reliability (ensuring that every byte of data transmitted is received), you should be using TCP regardless.
As you mentioned, UDP is more suitable for games, where 100% accurate real-time tracking of every object would use quite a large amount of bandwidth and is unnecessary (this is where slow connections encounter lag).
There is no special difference between a TCP port and a UDP port, beyond the type of connection being used (send the packet and forget it, UDP style, or negotiate a connection and sustain it, TCP style) and the service listening on the server side. e.g. TCP/25 would usually reveal a SMTP server, whereas UDP/25 would not.
Basically, modern TCP implementations are going to be just as fast as UDP, if you're keeping the connection alive. If TCP is having to resend a packet, you'd need to resend it in UDP too. Plus for UDP you're going to end up implementing the same reliability code (retransmission of dropped packets) that TCP has already implemented.

Difference between TCP and UDP?

What is the difference between TCP and UDP?
I know that TCP is used in the case of non-time critical applications, and UDP is used for games or applications that require fast transmission of data. I know that TCP is used for HTTP, HTTPs, FTP, SMTP, and Telnet. I know that UDP is used for DNS and DHCP.
But why? What characteristics of TCP and UDP make it useful for their respective use cases?
TCP is a connection oriented stream over an IP network. It guarantees that all sent packets will reach the destination in the correct order. This imply the use of acknowledgement packets sent back to the sender, and automatic retransmission, causing additional delays and a general less efficient transmission than UDP.
UDP is a connection-less protocol. Communication is datagram oriented. The integrity is guaranteed only on the single datagram. Datagrams reach destination and can arrive out of order or don't arrive at all. It is more efficient than TCP because it uses non ACK. It's generally used for real time communication, where a little percentage of packet loss rate is preferable to the overhead of a TCP connection.
In certain situations UDP is used because it allows broadcast packet transmission. This is sometimes fundamental in cases like DHCP protocol, because the client machine hasn't still received an IP address (this is the DHCP negotiaton protocol purpose) and there won't be any way to establish a TCP stream without the IP address itself.
From the Skullbox article:
TCP (Transmission Control Protocol) is the most commonly used protocol on the Internet.
The reason for this is because TCP offers error correction. When the TCP protocol is used there is a "guaranteed delivery." This is due largely in part to a method called "flow control." Flow control determines when data needs to be re-sent, and stops the flow of data until previous packets are successfully transferred. This works because if a packet of data is sent, a collision may occur. When this happens, the client re-requests the packet from the server until the whole packet is complete and is identical to its original.
UDP (User Datagram Protocol) is anther commonly used protocol on the Internet. However, UDP is never used to send important data such as webpages, database information, etc; UDP is commonly used for streaming audio and video. Streaming media such as Windows Media audio files (.WMA) , Real Player (.RM), and others use UDP because it offers speed! The reason UDP is faster than TCP is because there is no form of flow control or error correction. The data sent over the Internet is affected by collisions, and errors will be present. Remember that UDP is only concerned with speed. This is the main reason why streaming media is not high quality.
1) TCP is connection oriented and reliable where as UDP is connection less and unreliable.
2) TCP needs more processing at network interface level where as in UDP it’s not.
3) TCP uses, 3 way handshake, congestion control, flow control and other mechanism to make sure the reliable transmission.
4) UDP is mostly used in cases where the packet delay is more serious than packet loss.
Think of TCP as a dedicated scheduled UPS/FedEx pickup/dropoff of packages between two locations, while UDP is the equivalent of throwing a postcard in a mailbox.
UPS/FedEx will do their damndest to make sure that the package you mail off gets there, and get it there on time. With the post card, you're lucky if it arrives at all, and it may arrive out of order or late (how many times have you gotten a postcard from someone AFTER they've gotten home from the vacation?)
TCP is as close to a guaranteed delivery protocol as you can get, while UDP is just "best effort".
Reasons UDP is used for DNS and DHCP:
DNS - TCP requires more resources from the server (which listens for connections) than it does from the client. In particular, when the TCP connection is closed, the server is required to remember the connection's details (holding them in memory) for two minutes, during a state known as TIME_WAIT_2. This is a feature which defends against erroneously repeated packets from a preceding connection being interpreted as part of a current connection. Maintaining TIME_WAIT_2 uses up kernel memory on the server. DNS requests are small and arrive frequently from many different clients. This usage pattern exacerbates the load on the server compared with the clients. It was believed that using UDP, which has no connections and no state to maintain on either client or server, would ameliorate this problem.
DHCP - DHCP is an extension of BOOTP. BOOTP is a protocol which client computers use to get configuration information from a server, while the client is booting. In order to locate the server, a broadcast is sent asking for BOOTP (or DHCP) servers. Broadcasts can only be sent via a connectionless protocol, such as UDP. Therefore, BOOTP required at least one UDP packet, for the server-locating broadcast. Furthermore, because BOOTP is running while the client... boots, and this is a time period when the client may not have its entire TCP/IP stack loaded and running, UDP may be the only protocol the client is ready to handle at that time. Finally, some DHCP/BOOTP clients have only UDP on board. For example, some IP thermostats only implement UDP. The reason is that they are built with such tiny processors and little memory that the are unable to perform TCP -- yet they still need to get an IP address when they boot.
As others have mentioned, UDP is also useful for streaming media, especially audio. Conversations sound better under network lag if you simply drop the delayed packets. You can do that with UDP, but with TCP all you get during lag is a pause, followed by audio that will always be delayed by as much as it has already paused. For two-way phone-style conversations, this is unacceptable.
One of the differences is in short
UDP : Send message and dont look back if it reached destination, Connectionless protocol
TCP : Send message and guarantee to reach destination, Connection-oriented protocol
TCP establishes a connection before the actual data transmission takes place, UDP does not. In this way, UDP can provide faster delivery. Applications like DNS, time server access, therefore, use UDP.
Unlike UDP, TCP uses congestion control. It responses to the network load. Unlike UDP, it slows down when network congestion is imminent. So, applications like multimedia preferring constant throughput might go for UDP.
Besides, UDP is unreliable, it doesn't react on packet losses. So loss sensitive applications like multimedia transmission prefer UDP. However, TCP is a reliable protocol, so, applications that require reliability such as web transfer, email, file download prefer TCP.
Besides, in today's internet UDP is not as welcoming as TCP due to middle boxes. Some applications like skype fall down to TCP when UDP connection is assumed to be blocked.
Run into this thread and let me try to express it in this way.
TCP
3-way handshake
Bob: Hey Amy, I'd like to tell you a secret
Amy: OK, go ahead, I'm ready
Bob: OK
Communication
Bob: 'I', this is the first letter
Amy: First letter received, please send me the second letter
Bob: ' ', this is the second letter
Amy: Second letter received, please send me the third letter
Bob: 'L', this is the third letter
After a while
Bob: 'L', this the third letter
Amy: Third letter received, please send me the fourth letter
Bob: 'O', this the forth letter
Amy: ...
......
4-way handshake
Bob: My secret is exposed, now, you know my heart.
Amy: OK. I have nothing to say.
Bob: OK.
UDP
Bob: I LOVE U
Amy received: OVI L E
TCP is more reliable than UDP with even message order guaranteed, that's no doubt why UDP is more lightweight and efficient.
The Law of Leaky Abstractions
by Joel Spolsky
http://www.joelonsoftware.com/articles/LeakyAbstractions.html
Short and simple differences between Tcp and Udp protocol:
1) Tcp - Transmission control protocol and Udp - User datagram protocol.
2) Tcp is reliable protocol, Where as Udp is a unreliable protocol.
3) Tcp is a stream oriented, where as Udp is a message oriented protocol.
4) Tcp is a slower than Udp.
This sentence is a UDP joke, but I'm not sure that you'll get it. The below conversation is a TCP/IP joke:
A: Do you want to hear a TCP/IP joke?
B: Yes, I want to hear a TCP/IP joke.
A: Ok, are you ready to hear a TCP/IP joke?
B: Yes, I'm ready to hear a TCP/IP joke.
A: Well, here is the TCP/IP joke.
A: Did you receive a TCP/IP joke?
B: Yes, I **did** receive a TCP/IP joke.
TCP and UDP are transport layer protocol, Layer 4 protocol in OSI(open systems interconnection model). The main difference along with pros and cons are as following.
TCP
PROS:
Acknowledgment
Guaranteed Delivery
Connection based
Ordered packets
Congestion control
CONS:
Larger Packet
More bandwidth
Slower
Statefull
Consume memory
UDP
PROS:
Packets are smaller
Consume less bandwidth
Faster
Stateless
CONS:
No acknowledgment
No guaranteed delivery
Connectionless
No congestion control
No order packet
TLDR;
TCP - stream-oriented, requires a connection, reliable, slow
UDP - message-oriented, connectionless, unreliable, fast
Before we start, remember that all disadvantages of something are a continuation of its advantages. There only a right tool for a job, no panacea. TCP/UDP coexist for decades, and for a reason.
TCP
It was designed to be extremely reliable and it does its job very well. It's so complex because it accomplishes a hard task: providing a reliable transport over the unreliable IP protocol.
Since all TCP's complex logic is encapsulated into the network stack, you are free from doing lots of laborious, error-prone low-level stuff in the application layer.
When you send data over TCP, you write a stream of bytes to the socket at the sender side where it gets broken into packets, passed down the stack and sent over the wire. On the receiver side packets get reassembled again into a continous stream of bytes.
Maintaining this nice abstraction has a cost in terms of complexity and performance. If the 1st packet from the byte stream is lost, the receiver will delay processing of subsequent packets even those have already arrived (the so-called "head of line blocking").
In addition, in order to be reliable, TCP implements this:
TCP requires an established connection, which requires 3 round-trips ("infamous" 3-way handshake)
TCP has a feature called "slow start" when it gradually ramps up the transmission rate after establishing a connection to allow a receiver to keep up with data rate
Every sent packet has to be acknowledged or else a sender will stop sending more data
And on and on and on...
All this is exacerbated in slow unreliable wireless networks because TCP was designed for wired networks where delays are predictable and packet loss is not so common. In addition, like many people already mentioned, for some things TCP just doesn't work at all (DHCP). However, where relevant, TCP still does its work exceptionally well.
Using a mail analogy a TCP session is similar to telling a story to your secretary who breaks it into mails and sends over a crappy mail service to a publisher. On the other side another secretary assembles mails into a single piece of text. Some mails get lost, some get corrupted, so a very complex procedure is required for reliable delivery and your 10-page story can take a long time to reach your publisher.
UDP
UDP, on the other hand, is message-oriented, so a receiver writes a message (packet) to the socket and then it gets transmitted to a receiver as-is, without any splitting/assembling in the transport layer.
Compared to TCP, its specification is very straightforward. Essentially, all it does for you is adding a checksum to the packet so a receiver can detect its corruption. Everything else must be implemented by you, a software developer. Now read the voluminous TCP spec and try thinking of re-implementing even a small subset of it.
Some people went this way and got very decent results, to the point that HTTP/3 uses QUIC - a protocol based on UDP. However, this is more of an exception. Common applications of UDP are audio/video streaming and conferencing applications like Skype, Zoom or Google Hangout where loosing packets is not so important compared to a delay introduced by TCP.
Simple Explanation by Analogy
TCP is like this.
Imagine you have a pen-pal on Mars (we communicated with written letters back in the good ol' days before the internet).
You need to send your pen pal the seven habits of highly effective people. So you decide to send it in seven separate letters:
Letter 1 - Be proactive
Letter 2 - Begin with the end in mind...
etc.
etc..Letter 7 - Sharpen the Saw
Requirements:
You want to make sure that your pen pal receives all your letters - in order and that they arrive perfectly. If your pen pay receives letter 7 before letter 1 - that's no good. if your pen pal receives all letters except letter 3 - that also is no good.
Here's how we ensure that our requirements are met:
Confirmation Letter: So your pen pal sends a confirmation letter to say "I have received letter 1". That way you know that your pen pal has received it. If a letter does not arrive, or arrives out of order, then you have to stop, and go back and re-send that letter, and all subsequent letters.
Flow Control: Around the time of Xmas you know that your pen pal will be receiving a lot of mail, so you slow down because you don't want to overwhelm your pen pal. (Your pen pal sends you constant updates about the number of unread messages there are in penpal's mailbox - if your pen pal says that the inbox is about to explode because it is so full, then you slow down sending your letters - because your pen pal won't be able to read them.
Perfect arrival. Sometimes while you send your letter in the mail, it can get torn, or a snail can eat half of it. How do you know that all your letter has arrived in perfect condition? Well your pen pal will give you a mechanism by which you can check whether they've got the full letter and that it was the exactly the letter that you sent. (e.g. via a word count etc. ). a basic analogy.

What are examples of TCP and UDP in real life?

I know the difference between the two on a technical level.
But in real life, can anyone provide examples (the more the better) of applications (uses) of TCP and UDP to demonstrate the difference?
UDP: Anything where you don't care too much if you get all data always
Tunneling/VPN (lost packets are ok - the tunneled protocol takes care of it)
Media streaming (lost frames are ok)
Games that don't care if you get every update
Local broadcast mechanisms (same application running on different machines "discovering" each other)
TCP: Almost anything where you have to get all transmitted data
Web
SSH, FTP, telnet
SMTP, sending mail
IMAP/POP, receiving mail
EDIT: I'm not going to bother explaining the differences, since you state that you already know and every other answer explains it anyway :)
UDP is mailing a letter at the post office.
TCP is mailing a letter with a return receipt at the post office, except that the post master will organize the letters in-order-of mailing and only deliver them in-order.
Well, it was an attempt anyway.
TCP:
World Wide Web(HTTP)
E-mail (SMTP TCP)
File Transfer Protocol (FTP)
Secure Shell (SSH)
UDP:
Domain Name System (DNS)
Streaming media applications such as movies
Online multiplayer games
Voice over IP (VoIP)
Trivial File Transfer Protocol (TFTP)
REAL TIME APPLICATION FOR TCP:
Email:
Reason: suppose if some packet(words/statement) is missing we cannot understand the content.It should be reliable.
REAL TIME APPLICATION FOR UDP:
video streaming:
* **Reason: ***suppose if some packet(frame/sequence) is missing we can understand the content.Because video is collection of frames.For 1 second video there should be
25 frames(image).Even though we can understand some frames are missing due to our imagination skills. Thats why UDP is used for video streaming.
The classic standpoint is to consider TCP as safe and UDP as unreliable.
But when TCP-IP protocols are used in safety critical applications,
TCP is not recommended because it can stop on error for multiple reasons.
Whereas UDP lets the application software deal with errors, retransmission timers, etc.
Moreover, TCP has more processing overhead than UDP.
Currently, UDP is used in aircraft controls and flight instruments,
in the ARINC 664 standard also named AFDX (Avionics Full-Duplex Switched Ethernet).
In ARINC 664, TCP is optional but UDP is used with the RTOS (real time operating systems) designed for the ARINC 653 standard (high reliability control software in civil aircrafts).
For more information about real time controls using IP and UDP in AFDX,
you can read the pages 27 to 50 in
http://www.afdx.com/pdf/AFDX_Training_October_2010_Full.pdf
TCP
I will not send data anymore until i get an acknowledgment.
this process is slow
It is used for security purpose
example: web, sending mail, receiving mail etc
UDP
Here i have no headache with acknowledgment.
this process is faster but here data can be lost .
example : video streaming , online games etc
TCP + UDP = SMTP(example : mobile,telephone)
TCP guarantees (in-order) packet delivery. UDP doesn't.
TCP - used for traffic that you need all the data for. i.e HTML, pictures, etc.
UDP - used for traffic that doesn't suffer much if a packet is dropped, i.e. video & voice streaming, some data channels of online games, etc.
TCP is a connection oriented protocol, It establishes a path, or a virtual connection all the way through switches routers proxies etc and then starts any communication. Various mechanisms like routing djikstras shortest path algorithm exist to establish the virtual end to end connection. So it finds itself used while browsing HTML and other pages, making payments and web applications in general.
UDP is a connectionless protocol - it simply has a destination and nodes simply pass it along if it comes as best as they can. So packets arriving out of order, along various routes etc are common. So Instant messengers and similar software developers think UDP an ideal solution.
In real life if you want to throw data in the net, without worrying about time taken to reach, order of reaching use UDP. If you want a solid path before you start throwing packets, and want same order and latency for your data packets use TCP - I will use UDP for Torrents and TCP for PayPal!
TCP :
Transmission Control Protocol is a connection-oriented protocol, which means that it requires handshaking to set up end-to-end communications. Once a connection is set up, user data may be sent bi-directionally over the connection.
Reliable – Strictly only at transport layer, TCP manages message acknowledgment, retransmission and timeout. Multiple attempts to deliver the message are made. If it gets lost along the way, the server will re-request the lost part. In TCP, there's either no missing data, or, in case of multiple timeouts, the connection is dropped. (This reliability however does not cover application layer, at which a separate acknowledgement flow control is still necessary)
Ordered – If two messages are sent over a connection in sequence, the first message will reach the receiving application first. When data segments arrive in the wrong order, TCP buffers delay the out-of-order data until all data can be properly re-ordered and delivered to the application.
Heavyweight – TCP requires three packets to set up a socket connection, before any user data can be sent. TCP handles reliability and congestion control.
Streaming – Data is read as a byte stream, no distinguishing indications are transmitted to signal message (segment) boundaries.
Applications of TCP
World Wide Web, email, remote administration, and file transfer rely on TCP.
UDP :
User Datagram Protocol is a simpler message-based connectionless protocol. Connectionless protocols do not set up a dedicated end-to-end connection. Communication is achieved by transmitting information in one direction from source to destination without verifying the readiness or state of the receiver.
Unreliable – When a UDP message is sent, it cannot be known if it will reach its destination; it could get lost along the way. There is no concept of acknowledgment, retransmission, or timeout.
Not ordered – If two messages are sent to the same recipient, the order in which they arrive cannot be predicted.
Lightweight – There is no ordering of messages, no tracking connections, etc. It is a small transport layer designed on top of IP.
Datagrams – Packets are sent individually and are checked for integrity only if they arrive. Packets have definite boundaries which are honored upon receipt, meaning a read operation at the receiver socket will yield an entire message as it was originally sent.
No congestion control – UDP itself does not avoid congestion. Congestion control measures must be implemented at the application level.
Broadcasts – being connectionless, UDP can broadcast - sent packets can be addressed to be receivable by all devices on the subnet.
Multicast – a multicast mode of operation is supported whereby a single datagram packet can be automatically routed without duplication to very large numbers of subscribers.
Applications of UDP
Numerous key Internet applications use UDP, including: the Domain Name System (DNS), where queries must be fast and only consist of a single request followed by a single reply packet, the Simple Network Management Protocol (SNMP), the Routing Information Protocol (RIP) and the Dynamic Host Configuration Protocol (DHCP).
Voice and video traffic is generally transmitted using UDP. Real-time video and audio streaming protocols are designed to handle occasional lost packets, so only slight degradation in quality occurs, rather than large delays if lost packets were retransmitted. Because both TCP and UDP run over the same network, many businesses are finding that a recent increase in UDP traffic from these real-time applications is hindering the performance of applications using TCP, such as point of sale, accounting, and database systems. When TCP detects packet loss, it will throttle back its data rate usage. Since both real-time and business applications are important to businesses, developing quality of service solutions is seen as crucial by some.
Some VPN systems such as OpenVPN may use UDP while implementing reliable connections and error checking at the application level.
TCP is appropriate when you have to move a decent amount of data (> ~1 kB), and you require all of it to be delivered. Almost all data that moves across the internet does so via TCP - HTTP, SMTP, BitTorrent, SSH, etc, all use TCP.
UDP is appropriate when you have small messages which you can afford to lose, and would like to send them as efficiently as possible. One reason you might be able to afford to lose them is because you can re-send them if they get lost. The main example on the internet is DNS - DNS consists of small queries saying things like "what is the IP number for stackoverflow.com?", and the responses are correspondingly small. Computers make a lot of these queries, so they should be made efficiently, but if they get lost en route, it's easy to time out and re-send them.
TCP guarantees packet delivery AND order. Order is almost as important as the delivery in the first place when reconstructing data for files such as executables, etc.
UDP does not guarantee delivery NOR order. Packets can arrive (or not!) in any order.
Common uses for TCP include file transfer where the integrity of the packets is paramount. Voice/video applications can afford to lose some data while still maintaining acceptable quality, and so usually use UDP.
One additional thought on some of the comments above that talks about ordered delivery.... It must be clarified that the destination computer may receive packets out of order on the wire, but the TCP at the destination is responsible for "rearranging out-of-order data" before passing it on to the upper layers of the stack. When you say TCP guarantees ordered packet delivery, what that means is it will deliver packets in correct order to the upper layers of the stack.
SCTP vs TCP vs UDPServices/Features SCTP TCP UDP
Connection-oriented yes yes no
Full duplex yes yes yes
Reliable data transfer yes yes no
Partial-reliable data transfer optional no no
Ordered data delivery yes yes no
Unordered data delivery yes no yes
Flow control yes yes no
Congestion control yes yes no
ECN capable yes yes no
Selective ACKs yes optional no
Preservation of message boundaries yes no yes
Path MTU discovery yes yes no
Application PDU fragmentation yes yes no
Application PDU bundling yes yes no
Multistreaming yes no no
Multihoming yes no no
Protection against SYN flooding attacks yes no n/a
Allows half-closed connections no yes n/a
Reachability check yes yes no
Psuedo-header for checksum no (vtags) yes yes
Time wait state vtags 4-tuple n/a
Since tcp usages are pretty straightforward from other answers, I'll mention some interesting UDP use-cases:
1)DHCP - Dynamic Host Configuration Protocol, which is being used in order to dynamically assign IP address and some other network configuration to the connecting devices. In simple words, this protocol allows you just connect to the network cable(or wifi) and start using the internet, without any additional configurations. DHCP uses UDP protocol. Since the settings request message is being broadcasted from the host and there is no way to establish a TCP connection with DHCP server(you don't know it's address) it's impossible to use TCP instead.
2)Traceroute - well-known network diagnostic tool which allows you to explore which path in the network your datagram passes to reach it's destination(and how much time it takes). By default, it works by sending UDP datagram with unlikely destination port number(ranging from 33434 to 33534) to the destination with the ttl(time-to-live) field set to 1. When the router somewhere in the network gets such datagram - it finds out that the datagram is expired. Then, the router drops the datagram and sends to the origin of the datagram an ICMP(Internet Control Message Protocol) error message indicating that the datagram's ttl was expired and containing router's name and IP address. Each time the host sends datagrams with higher and higher TTL, thus increasing the network part which it succeeds to overcome and getting new ICMP messages from new routers. When it eventually reaches it's destination(datagrams TTL is big enough to allow it),- the destination host sends 'Destination port unreachable' ICMP message to the origin host. This way, Traceroute knows that the destination was reached. Since the TCP guarantees segments delivery it would be at least inefficient to use it instead of UDP which, in turn, allows datagram to be just dropped without any resend attempts(resend is implemented on the higher level, with continuously increasing TTL as described above).
TCP: will get there in meaningful order
UDP: god knows (maybe)
UDP is applied a lot in games or other Peer-to-peer setups because it's faster and most of the time you don't need the protocol itself to make sure everything gets to the destination in the original order (UDP does not garantee packet delivery or delivery order).
Web traffic on the other hand is over TCP. (I'm not sure here but I think it has to do with the way the HTTP protocol is built)
Edited because I failed at UDP.
Real life examples of both TCP and UDP
tcp -> a phone call, sms or anything specific to destination
UDP -> a FM radio channel (AM), Wi-Fi.

Resources