<p>你这里有很多问题。首先,通过在服务器端使用<code>connect</code>,您告诉操作系统您将只与IP地址“192.168.67.42”端口5000通信。这可能不是你想要的。(服务器通常会与任何客户机想要与其交谈的内容交谈。)</p>
<p>其次,通过不在客户机中指定<code>SOCK_DGRAM</code>,您将获得默认的套接字类型,即<code>SOCK_STREAM</code>。这意味着您的客户机正试图<code>connect</code>到<em>TCP</em>端口80上的服务器,而不是UDP端口80(这两个名称空间是完全独立的)。</p>
<p>对于UDP“会话”,双方都需要一个IP地址和一个端口号。如果不特别指定端口,操作系统将准随机地为您选择一个。为了连接客户机和服务器,他们必须至少就其中一个达成一致。</p>
<p>所以一个典型的UDP服务器会<code>bind</code>到一个众所周知的端口(可能您打算5000个这样做)。然后客户机可以<code>connect</code>到该端口的服务器。代码如下所示(<em>sans</em>错误处理):</p>
<p>服务器端:</p>
<pre><code># Create socket
s = socket(AF_INET, SOCK_DGRAM)
# Bind to our well known port (leave address unspecified
# allowing us to receive on any local network address)
s.bind(('', 5000))
# Receive from client (so we know the client's address/port)
buffer, client_addr = s.recvfrom(1024)
# Now we can send to the client
s.sendto(some_buffer, client_addr)
</code></pre>
<p>客户机与您的位置很接近,但您应该先从客户机向服务器发送一些数据,以便服务器知道您的地址:</p>
<pre><code>s = socket(AF_INET, SOCK_DGRAM)
# Create connection to server (the OS will automatically
# bind a port for the client)
s.connect((host, port))
# Send dummy data to server so it knows our address/port
s.send(b'foo')
buffer = s.recv(1024)
</code></pre>
<p>注意,因为您在客户端使用了<code>connect</code>,所以您已经永久地指定了对等方的地址,不需要使用<code>recvfrom</code>和<code>sendto</code>。</p>