python如何创建UDP服务器和客户端?
python如何创建UDP服务器和客户端?
本文教程操作环境:windows7系统、Python3.9.1,DELLG3电脑。
1、创建UDP服务端的基本步骤
(1)创建套接字并绑定地址
(2)开始监听连接
(3)收发数据
(4)关闭套接字
importsocket
HOST=''
PORT=3214
sk=socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
sk.bind((HOST,PORT))
data=True
whiledata:
data,addr=sk.recvfrom(1024)
ifdata==b'bye':
break
print"RecieveData:",data.decode('utf-8')
sk.sendto(data,addr)
sk.close()
2、创建UDP客户端的基本步骤
(1)创建套接字
(2)收发数据
(3)关闭套接字
importsocket
HOST='127.0.0.1'
PORT=3214
sk=socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
data='hello'
whiledata:
sk.sendto(data,(HOST,PORT))
ifdata=="bye":
break
data,addr=sk.recvfrom(1024)
print"RecvData:",data
data=raw_input('Pleasemessage:\n')
sk.close()
#tcpclient与udpclient区别
#建立socket时的区别
#tcp需要链接服务端
#收发数据方法不同
说明:由于UDP服务器不是面向连接的,所以不用像TCP服务器那样做那么多设置工作。事实上,并不用设置什么东西,直接等待进来的连接就好了。
在编程通信的端口上,我们知道有服务端和客户端两种。在之前的学习中接触过两种通信协议,UDP相比较而言,由于自身无连接的特性,所以在设置方法上没有那么多的步骤。
以上就是python创建UDP服务器和客户端的方法,大家在看完相关的步骤后,就可以动手尝试下操作了。对于难一点的TCP创建,也可以进行一次练习。更多Python学习教程请关注IT培训机构:千锋教育。

猜你喜欢LIKE
相关推荐HOT
更多>>
python字符串需要注意的语法问题
python字符串需要注意的语法问题语法错误是经常发生的一个错误。当一个程序包含非法的Python代码时,会产生语法错误。举例来说,在包含单引号的...详情>>
2023-11-14 18:23:24
python函数标注是什么
python函数标注是什么在参数的使用方法中,还有一种解包的情况是需要我们掌握的。比如,将列表或者字典的值转换为函数的参数,就需要用到参数解...详情>>
2023-11-14 14:13:35
python正负索引的使用
python正负索引的使用本文教程操作环境:windows7系统、Python3.9.1,DELLG3电脑。1、说明使用正索引(从左至右)、负索引(从右至左)访问元素,时...详情>>
2023-11-14 13:45:04
python垃圾回收的机制过程
python垃圾回收的机制过程本文教程操作环境:windows7系统、Python3.9.1,DELLG3电脑。1、步骤(1)收集所有容器对象(list,dict,tuple,customClas...详情>>
2023-11-14 13:05:15热门推荐
python中title函数的作用
沸python中集合与列表有什么区别?
热python中uuid模块是什么?
热python中使用_setattr_()
新python中scikit-learn是什么?
python Faker库如何使用?
python behold库是什么?
python中ndarray是什么?
python UDP编程是什么意思?
python如何创建UDP服务器和客户端?
python字符串需要注意的语法问题
python如何配置Logging处理器
pythonos模块有几种用法?
python如何定制日志输出格式
技术干货






