如何解决如何在不同的网络上使用python socket
我一直在尝试使用 ipv6 地址发送文件,但是每当我更改网络时,它都无法连接到这两个代码。 客户
import os
import time
SEPARATOR = "<SEPARATOR>"
BUFFER_SIZE = 4096
host = 'x' # ipv6 address
port = 5001
filename = input('File Name:')
filesize = os.path.getsize(filename)
s = socket.socket(socket.AF_INET6,socket.SOCK_STREAM,0)
print(f"[+] Connecting to {host}:{port}")
s.connect((host,port,0))
print("[+] Connected.")
s.send(f"{filename}{SEPARATOR}{filesize}".encode())
with open(filename,"rb") as f:
for _ in range(filesize):
# read the bytes from the file
bytes_read = f.read(BUFFER_SIZE)
if not bytes_read:
break
s.sendall(bytes_read)
s.close()
服务器
import socket
import time
import os
# device's IP address
SERVER_HOST = "::"
SERVER_PORT = 5001
BUFFER_SIZE = 4096
SEPARATOR = "<SEPARATOR>"
s = socket.socket(socket.AF_INET6,0)
s.bind((SERVER_HOST,SERVER_PORT))
s.listen(5)
print(f"[*] Listening as {SERVER_HOST}:{SERVER_PORT}")
client_socket,address = s.accept()
print(f"[+] {address} is connected.")
received = client_socket.recv(BUFFER_SIZE).decode()
filename,filesize = received.split(SEPARATOR)
filename = os.path.basename(filename)
filesize = int(filesize)
with open(filename,"wb") as f:
for _ in range(filesize):
# read 1024 bytes from the socket (receive)
bytes_read = client_socket.recv(BUFFER_SIZE)
if not bytes_read:
break
f.write(bytes_read)
client_socket.close()
# close the server socket
s.close()
提前致谢。 我刚刚开始学习 Python,所以我觉得我可能需要完整的代码或 YouTube 教程链接。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。