![图片[1]-五分钟搞定Python网络编程实现TCP和UDP连接-uusu优素-乐高,模型,3d打印,编程](http://uusucn.zbbe.cn/wp-content/uploads/2024/01/5d32ac2e39de5414.jpg)
Python网络编程实现TCP和UDP连接, 使用socket模块, 所有代码在python3下测试通过。
实现TCP
#!/usr/bin/envpython3
#-*-coding:utf-8-*-
importsocket
#创建一个socket:
s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
#建立连接:
s.connect(('www.baidu.com',80))
#发送数据:
s.send(b'GET/HTTP/1.1\r\nHost:www.baidu.com\r\nConnection:close\r\n\r\n')
#接收数据:
buffer=[]
whileTrue:
#每次最多接收1k字节:
d=s.recv(1024)
ifd:
buffer.append(d)
else:
break
data=b''.join(buffer)
#关闭连接:
s.close()
header,html=data.split(b'\r\n\r\n',1)
print(header.decode('utf-8'))
#把接收的数据写入文件:
withopen('sina.html','wb')asf:
f.write(html)
实现UDP连接
服务端:
#!/usr/bin/envpython3
#-*-coding:utf-8-*-
importsocket
s=socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
#绑定端口:
s.bind(('127.0.0.1',9999))
print('BindUDPon9999...')
whileTrue:
#接收数据:
data,addr=s.recvfrom(1024)
print('Receivedfrom%s:%s.'%addr)
reply='Hello,%s!'%data.decode('utf-8')
s.sendto(reply.encode('utf-8'),addr)
#!/usr/bin/envpython3
#-*-coding:utf-8-*-
importsocket
s=socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
fordatain[b'Michael',b'Tracy',b'Sarah']:
#发送数据:
s.sendto(data,('127.0.0.1',9999))
#接收数据:
print(s.recv(1024).decode('utf-8'))
s.close()原文来自:https://www.py.cn © 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END
















































暂无评论内容