TCP 和 UDP 套接字之间的区别 [英] Difference between TCP and UDP sockets

查看:72
本文介绍了TCP 和 UDP 套接字之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 TCP 套接字(sock_stream)和 UDP 套接字(数据报)建立连接有什么区别.到目前为止,我认为像我们可以只为 TCP 套接字使用 connect 函数创建连接.但是,可以与 UDP 套接字建立连接.到目前为止,我还不知道如何与 UDP 套接字建立连接.这两者有什么区别?

What is the difference between making a connection with TCP sockets (sock_stream) and UDP sockets (datagram). Up to now, I think like we can create a connection using connect function only for TCP sockets. But, it is possible for making a connection with UDP sockets. Up to now I didn't know about making a connection with UDP sockets. What is the difference between these two?

        int tcpsock = socket(AF_INET, SOCK_STREAM, 0);
        connect(tcpsock,(struct sockaddr*)&sa,sizeof(sa));

        int udpsock = socket(AF_INET, SOCK_DGRAM, 0);
        connect(udpsock,(struct sockaddr*)&sa,sizeof(sa));  // How ?

UDP 是无连接的.那么如果我们使用 UDP 怎么可能建立一个类似于 TCP 的连接?

UDP is connectionless. so if we use UDP how it is possible to make a connection similar to TCP?

我已经知道 TCP 和 UDP 之间的区别.我的疑问是,UDP 是connectionless 那么connect函数如何返回成功?

I already know about the difference between TCP and UDP. My doubt is, UDP is connectionless then how connect function returns success?

推荐答案

UDP 中的 connect() 函数(a)告诉 UDP 将所有数据报发送到哪里,因此您可以使用 send() 而不是 sendto(),并且 (b) 充当传入数据报的过滤器,因此您可以使用 recv() 而不是 recvfrom().它在网络上不做任何事情:它只是一个本地操作.它总是返回零,因为它不会失败.然而,发送到一个不存在的目标可能会失败......

The connect() function in UDP (a) tells UDP where to send all datagrams, so you can use send() instead of sendto(), and (b) acts as a filter on incoming datagrams, so you can use recv() instead of recvfrom(). It doesn't do anything on the network: it's just a local operation. It always returns zero because it can't fail. However sending to a non-existent target can fail ...

一切都记录在案.

这篇关于TCP 和 UDP 套接字之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆