设为首页 加入收藏

TOP

Python网络编程实现TCP和UDP连接
2018-08-22 06:07:56 】 浏览:124
Tags:Python 网络编程 实现 TCP UDP 连接

Python网络编程实现TCP和UDP连接


实现TCP


#!/usr/bin/env python3
# -*- coding: utf-8 -*-


import socket


# 创建一个socket:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)


# 建立连接:
s.connect(('www.sina.com.cn', 80))


# 发送数据:
s.send(b'GET / HTTP/1.1\r\nHost: www.sina.com.cn\r\nConnection: close\r\n\r\n')


# 接收数据:
buffer = []
while True:
    # 每次最多接收1k字节:
    d = s.recv(1024)
    if d:
        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'))


# 把接收的数据写入文件:
with open('sina.html', 'wb') as f:
    f.write(html)


实现UDP连接


服务端:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-


import socket


s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)


# 绑定端口:
s.bind(('127.0.0.1', 9999))


print('Bind UDP on 9999...')


while True:
    # 接收数据:
    data, addr = s.recvfrom(1024)
    print('Received from %s:%s.' % addr)
    reply = 'Hello, %s!' % data.decode('utf-8')
    s.sendto(reply.encode('utf-8'), addr)


客户端:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-


import socket


s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)


for data in [b'Michael', b'Tracy', b'Sarah']:
    # 发送数据:
    s.sendto(data, ('127.0.0.1', 9999))
    # 接收数据:
    print(s.recv(1024).decode('utf-8'))


s.close()


】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇Java for循环对集合的遍历 下一篇基于UDP协议的密码验证

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目