如何在不同的网络上使用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 (将#修改为@)