Python - UDP 客户端 [英] Python - UDP client

查看:51
本文介绍了Python - UDP 客户端的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在阅读 Python book 并遇到以下示例:

I am currently reading a Python book and came across the following example:

import socket
target_host = "127.0.0.1"
target_port = 80

# create a socket object
client = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

# send some data
client.sendto("AAABBBCCC",(target_host,target_port))

# receive some data
data, addr = client.recvfrom(4096)

print data

如果我理解正确,我正在 UDP 端口 80 上构建我自己的环回 IP 地址的侦听器.我的问题是,它有什么用处以及如何测试"它?(意思是如何读取发送的AAABBBCCC")?

If I understood it right, I am building a listener to my own loop-back IP address on the UDP port 80. My question is, what is it good for and how I can "test" it? (Meaning how can I read the sent "AAABBBCCC")?

谢谢

推荐答案

你需要运行一个服务器来监听你的发件人发送到的端口.这里有一个很好的解释.

You need to run a server to listen on the port your sender sent to. there is a good explanation here.

一个很好的例子是(基于上面的链接):

A nice example for you is (based on the above link):

import socket

UDP_IP = "127.0.0.1"
UDP_PORT = 80

sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.bind((UDP_IP, UDP_PORT))

while True:
   data, addr = sock.recvfrom(1024) #buffer of 1024 bytes
   print "received message: ", data

您需要先运行服务器,以便它开始侦听,然后再单独运行您的客户端.

You need to run the server first so it start listening and than run your client separately.

这篇关于Python - UDP 客户端的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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