UDP
client
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_DRGAM) # AF_INET 用于Internet进程通讯,AF_UNIX 用于同一台机器的线程通讯;
# SOCK_STREAM (流式套接字,主要用于TCP 协议)
# SOCK_DGRAM (数据报套接字, 主要用于UDP协议)
s.sendto('hello'.encode('utf8'), ('0.0.0.0', 8080)) # 第一个参数是要发送的数据,二进制格式;第二个是目标ip及端口号,是一个元组。
s.close()
server
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_DRGAM)
s.bind(('0.0.0.0', 8080))
content = s.recvfrom(1024) # 接收长度
print('从{} 端口{} 接收到{}'.format(content[1][0],content[1][1],content[0]))
s.close()
TCP
client
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(('0.0.0.0', 8080)) # 注意目标服务器此时必须是启动的,否则会报错,tcp 要先连接成功了,才发数据
s.sent('hello'.encode)
s.close()
server
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(('0.0.0.0', 8080))
s.listen(128) # 监听,把socket 变成一个被动监听socket
client_socket, client_addr = s.accept()
x = client_socket.recv(1024) # 每次拿长度
print('接收到的了{}客户端{}端口号发送的数据,内容是:{}'.format(client_addr[0], client_addr[1], x))
下载文件
client
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(('0.0.0.0', 8080))
file_name = input('请输入要下载的文件名: ')
s.sent(file.name.encode('utf8'))
with open(file_name, 'wb') as file:
content = s.recv(1024)
if not content:
break
file.write(content)
s.close()
server
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STRAM)
s.bind(('0.0.0.0', 8080))
client_socket, client_addr = s.accept()
filename = client_socket.recv(1024).decode('utf8')
print('接收到了来着{}:{}的数据,内容是:{}'.format(client_addr[0], client_addr[1], filename))
if os.path.isfile(filename):
# print('watting sending')
with open(filename, 'rb') as file:
# print(file.read())
content = file.read()
client_socket.send(content)
else:
print('file not exist')
参考:
2020千锋Python入门视频全套全开源(最新版)
python之socket编程