简体   繁体   English

如何修复Windows拒绝错误以进行局域网文件传输

[英]How to fix windows decline error for lan file transfer

I'm a 14 year old beginner in software design but have good knowledge in python basic and acute amounts in networking. 我是14岁的软件设计初学者,但是对python基本知识和网络知识非常了解。 i recently got a raspberry pi 3 b+ brand new and am trying to make a python program that will allow me to transmit information input from my hp PC to my pi so it can display the info, this project is to help me with school, i have code typed and it runs but when i try to run the "client code", this is so my pi can receive the input data, i get an error saying that the device has declined my connection request, what should i do to fix the issue? 我最近有一个全新的raspberry pi 3 b +,正在尝试制作一个python程序,该程序将允许我将hp PC的信息输入传输到pi,以便它可以显示信息,该项目是为了帮助我上学,我输入了代码并运行,但是当我尝试运行“客户端代码”时,这是我的pi可以接收输入数据的错误,我收到一条错误消息,说设备拒绝了我的连接请求,我该怎么做才能解决问题? if you want to see the code i can post it, but i'm not sure if that is necessary. 如果您想查看代码,我可以发布它,但是我不确定是否有必要。

i only tried changing the port number in both programs, since that is not the issue and i' new to LAN and networking, i haven't tried anything else. 我只是尝试在两个程序中更改端口号,因为这不是问题,并且我是LAN和网络的新手,所以我没有尝试过其他任何方法。

as requested my code is:(not HTML, CSS, or HTML. it's just easier to use that interface. 根据要求,我的代码是:(不是HTML,CSS或HTML。使用该界面更容易。

 # send.py import socket # Import socket module port = 60000 # Reserve a port for your service. s = socket.socket() # Create a socket object host = socket.gethostname() # Get local machine name s.bind((host, port)) # Bind to the port s.listen(5) # Now wait for client connection. print 'Server listening....' while True: conn, addr = s.accept() # Establish connection with client. print 'Got connection from', addr data = conn.recv(1024) print('Server received', repr(data)) filename='mytext.txt' f = open(filename,'rb') l = f.read(1024) while (l): conn.send(l) print('Sent ',repr(l)) l = f.read(1024) f.close() print('Done sending') conn.send('Thank you for connecting') conn.close() # recieve.py import socket # Import socket module s = socket.socket() # Create a socket object host = socket.gethostname() # Get local machine name port = 60000 # Reserve a port for your service. s.connect((host, port)) s.send("Hello server!") with open('received_file', 'wb') as f: print 'file opened' while True: print('receiving data...') data = s.recv(1024) print('data=%s', (data)) if not data: break # write data to a file f.write(data) f.close() print('Successfully get the file') s.close() print('connection closed') 

Unfortunately, this answer requires Python 3.5+. 不幸的是,这个答案需要Python 3.5+。

Before running this code please make sure you've worked out which IP you will be using for your server and client (help at the bottom). 在运行此代码之前,请确保已确定要用于服务器和客户端的IP(底部的帮助)。

Step 1 - Ensure a simple ping works 第1步-确保简单的ping操作

Server code: 服务器代码:

import socket

# FIND IP

# The IP to use will be different depending
# on whether you have WiFi or Ethernet, so
# you need to choose whichever one that is
ips = socket.gethostbyname_ex(socket.gethostname())[-1]

print(*[f"{i}: {j}" for i, j in enumerate(ips)], sep="\n")

ip = ips[int(input(" > "))]

# SELECT PORT

port = 10000


#SETUP SERVER

# Create server socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.bind((ip, port))

# A queue of 1 clients is more than enough for our application
sock.listen(1)

print(f"Listening on {ip}:{port}")

while True:
    try:
        (clientsock, address) = sock.accept()

        # so if there's nothing to read we don't wait too long
        clientsock.settimeout(0.01)

        ping_string = clientsock.recv(5).decode()

        if ping_string == "ping!":
            print("ping!")

            clientsock.sendall(b"ping!")

        else:
            print("no ping!")
            print(ping_string)

            clientsock.sendall(b"nopng")

        clientsock.shutdown(1)
        clientsock.close()

    except KeyboardInterrupt:
        # Add a way to safely exit the infinite loop
        break

sock.close()

Client code: 客户代码:

import socket

# GET IP

print("IP of server")
ip = input(" > ")

# SELECT PORT

port = 10000


# SETUP SOCKET

# Create server socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((ip, port))

print(f"Conencted to {ip}:{port}")

# so if there's nothing to read we don't wait too long
sock.settimeout(0.01)

sock.sendall(b"ping!")

ping_string = sock.recv(5).decode()

if ping_string == "ping!":
    print("ping!")

else:
    print("no ping!")

sock.close()

OUTPUT: 输出:

Server: 服务器:

0: 192.168.56.1
1: 192.168.1.151
 > 1
Listening on 192.168.1.151:10000

Client: 客户:

Type ip of server
 > 192.168.1.151
Conencted to 192.168.1.151:10000
ping!

If this doesn't work, make sure your computer can ping your raspberry pi, and vice versa. 如果这不起作用,请确保您的计算机可以ping通您的树莓派,反之亦然。 Go into CMD (I presume your HP PC is Windows) and type ping ____ (replacing ____ with the internal ip address of your raspberry pi. 进入CMD(假定您的HP PC是Windows),然后键入ping ____ (用树莓派的内部ip地址替换____)。

If the terminal doesn't appear to be pinging something, you need to go onto your computer and raspberry pi to find they're internal ips, which you can find out how to do online. 如果终端似乎无法ping通某些内容,则需要转到计算机和树莓派上查找它们是内部 ip,您可以找到如何在线进行操作。

Step 2 - The fun part 第2步-有趣的部分

We're now going to setup your file server. 现在,我们将设置您的文件服务器。

Server code: 服务器代码:

import socket

# OPEN FILE TO SEND ACROSS
with open("filesend.txt", mode="rb") as file:
    file_string = file.read()

# FIND IP

# The IP to use will be different depending
# on whether you have WiFi or Ethernet, so
# you need to choose whichever one that is
ips = socket.gethostbyname_ex(socket.gethostname())[-1]

print(*[f"{i}: {j}" for i, j in enumerate(ips)], sep="\n")

ip = ips[int(input(" > "))]

# SELECT PORT

port = 10000


#SETUP SERVER

# Create server socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.bind((ip, port))

# A queue of 1 clients is more than enough for our application
sock.listen(1)

print(f"Listening on {ip}:{port}")

while True:
    try:
        (clientsock, address) = sock.accept()

        # so if there's nothing to read we don't wait too long
        clientsock.settimeout(0.01)

        # send length
        clientsock.sendall((str(len(file_string)) + ".").encode())
        clientsock.sendall(file_string)

        print("Sent file!")

        response_code = clientsock.recv(1).decode()

        if response_code != "0":
            print("ERROR! response was not 0")
            print(response_code)


        clientsock.shutdown(1)
        clientsock.close()

    except KeyboardInterrupt:
        # Add a way to safely exit the infinite loop
        break

sock.close()

Client code: 客户代码:

import socket

# SELECT IP

print("IP of server")
ip = input(" > ")

# SELECT PORT

port = 10000


# SETUP SOCKET

# Create server socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((ip, port))

print(f"Conencted to {ip}:{port}")

# so if there's nothing to read we don't wait too long
sock.settimeout(0.01)

# Get length of file sent across
len_string = ""
c = ""
while c != ".":
    c = sock.recv(1).decode()
    len_string += c

length = int(len_string[:-1])

file_string = sock.recv(length)

# send a status code back to the server
sock.sendall(b"0")

with open("filerecv.txt", mode="wb") as file:
    file.write(file_string)

print(file_string.decode())

sock.close()

OUTPUT: 输出:

Server: 服务器:

0: 192.168.56.1
1: 192.168.1.151
 > 1
Listening on 192.168.1.151:10000

Client: 客户:

IP of server
 > 192.168.1.151
Conencted to 192.168.1.151:10000
THIS IS A TEST!

Once again, ensure the ip you tell the client to connect to is the same as the one you have selected from the list provided in the server script. 再次确保您告诉客户端连接的IP地址您从服务器脚本提供的列表中选择的IP地址相同 Also ensure that the ip address can be connected to, ie don't use the one for when the pc's on WiFi if it's currently on Ethernet. 另外,还要确保可以连接IP地址,即如果PC当前在以太网上,则不要在PC处于WiFi时使用该IP地址。

Hope this works for you. 希望这对您有用。 Any issues leave down in the comments :) 任何问题都留在评论中:)

EDIT 编辑

WINDOWS 视窗

Sample output from ipconfig : ipconfig示例输出:

> ipconfig

Windows IP Configuration


Ethernet adapter Ethernet:

   Connection-specific DNS Suffix  . : home
   IPv6 Address. . . . . . . . . . . : 2a00:23c6:6586:2400:e47a:c60e:812b:1123
   IPv6 Address. . . . . . . . . . . : fdaa:bbcc:ddee:0:e47a:c60e:812b:1123
   Temporary IPv6 Address. . . . . . : 2a00:23c6:6586:2400:d1fe:95f5:27c3:c4b8
   Temporary IPv6 Address. . . . . . : fdaa:bbcc:ddee:0:d1fe:95f5:27c3:c4b8
   Link-local IPv6 Address . . . . . : fe80::e47a:c60e:812b:1123%19
   IPv4 Address. . . . . . . . . . . : 192.168.1.151
   Subnet Mask . . . . . . . . . . . : 255.255.255.0
   Default Gateway . . . . . . . . . : fe80::8aa6:c6ff:fe23:7a15%19
                                       192.168.1.254

You're looking for this line: 您正在寻找以下行:

   IPv4 Address. . . . . . . . . . . : 192.168.1.151

And the IP is whatever value is at the end (eg 192.168.1.151 ) IP是末尾的任何值(例如192.168.1.151

FIND THE IP OF YOUR RASPBERRY PI 查找您的树莓派IP

Unless you've changed some advanced settings your Raspberry Pi's hostname will be raspberrypi , or raspberrypi.local . 除非您更改了一些高级设置,否则Raspberry Pi的主机名将是raspberrypiraspberrypi.local I've seen both. 我都看过 If you want to know the IP address, use the Python script below, and try to ping all the IPs from the list it prints to find out which one IP is actually used by the Pi. 如果您想知道IP地址,请使用下面的Python脚本,并尝试从打印的列表中ping所有IP,以找出Pi实际使用的IP。

Run this on your PC: 在您的PC上运行:

import socket

host1 = "raspberrypi"
host2 = "raspberrypi.local"

try:
    ip1 = socket.gethostbyname_ex(host1)[-1]
except:
    ip1 = []

try:
    ip2 = socket.gethostbyname_ex(host2)[-1]
except:
    ip2 = []

print(list(set(ip1+ip2)))

Any more issues, please let me know :) 还有其他问题,请让我知道:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何修复 Windows 机器中的 os.path 错误? - How to fix os.path error in windows machine? 如何修复错误:Windows 上的“AttributeError: module 'tensorflow' has no attribute 'contrib'” - How to fix error :“ AttributeError: module 'tensorflow' has no attribute 'contrib' ” on Windows 如何修复Windows中的UnicodeDecodeError? - How to fix this UnicodeDecodeError in Windows? 如何将文件从 AWS EC2 Amazon Linux 虚拟环境传输到本地(Windows)? - How do I transfer a file from a AWS EC2 Amazon Linux Virtual Env to local (windows)? 如何修复文件名或其路径中的语法错误? - how can i fix the syntax error in the file name or its path? 不知道如何修复popen,“无效的文件对象”错误 - Dont know how to fix popen ,“Invalid file object” error 在多个远程服务器(windows)之间传输文件的最佳方式 - Best Way to transfer file between multiple remote server(windows) 如何在 django 中设置 static 文件时修复 static 标签无效错误? - How to fix static tag is invalid error in setting a static file in django? 使用open()读取文件时如何修复EOF错误 - How to fix EOF Error when reading a file using with open() 如何在加载 MNIST 数据集时修复“没有这样的文件或目录”错误 - How to fix 'No such file or directory' error while loading MNIST dataset
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM