我在PC上访问了树莓派(Windows 10)。 服务器正在树莓派上运行,我想从PC(客户端在我的PC上运行,而不是在树莓派上)向服务器发送数据。
client.py
import socket
mysoc=socket.socket()
mysoc.connect(("xxx.xxx.xxx.xxx",1234)) //ip address of raspberrypi
while 1:
s=input("Enter command")
mysoc.sendall(s.encode())
if s==exit:
break
mysoc.close()
server.py
import socket
from gpiozero import LED
led=LED(17)
server_soc=socket.socket()
server_soc.bind(("",1234))
server_soc.listen(5)
print("Listening to client ...")
conn,addr=server_soc.accept()
print("connected to client:",addr)
while 1:
data=conn.recv(1024)
print(data)
if data==b"on\n":
print("LED is on")
led.on()
elif data==b"off\n":
print("LED is off")
led.off()
else:
break
conn.close()
server_soc.close()
执行client.py时出现以下错误。
>>>
= RESTART: C:\Users\Lenovo\AppData\Local\Programs\Python\Python38-32\My_Programs\client.py
Enter commandon
Enter commandoff
Enter commandon
Traceback (most recent call last):
File "C:\Users\Lenovo\AppData\Local\Programs\Python\Python38-32\My_Programs\client.py", line 7, in <module>
mysoc.sendall(s.encode())
ConnectionAbortedError: [WinError 10053] An established connection was aborted by the software in your host machine
>>>
server.py
>>> %Run server_control_led.py
Listening to client ...
connected to client: ('xxx.xxx.xxx.x', 50603) //ip address of my pc
b'on'
>>>
The server receives the first data and stops listening. I tried to disable antivirus and firewall but the issue still exists. I unable to figure the root cause of this closing connection. whether issue is on the server side or client-side. I am using putty and xming server and python code. I tried doing some changes in inbound and outbound rules in the firewall but still doesn't work. what should be configured?
答案 0 :(得分:1)
您应该在客户的第6行中指定加密的类型。您应该使用mysoc.sendall(s.encode())
而不是mysoc.sendall(s.encode('utf-8'))
。如果您不想使用utf-8,则可以始终传递其他编码方法,例如ascii。
-更新。在第7行中还有另一个错误,您尝试将s
与字符串进行比较,但忘了加上引号:
您的代码:
if s==exit:
更正:
if s=="exit":
-Update#2:我刚刚发现了实际的错误:您没有在服务器端正确解码字符串,因此条件语句不会将命令标识为“ on”或“ off”,而是某种形式否则,这就是服务器在收到第一条消息后退出的原因。这是固定代码: (服务器)
import socket
server_soc=socket.socket()
server_soc.bind(("",1234))
server_soc.listen(5)
print("Listening to client ...")
conn,addr=server_soc.accept()
print("connected to client:",addr)
while 1:
data=conn.recv(1024)
print(data)
data=data.decode('utf-8')
if data=="on":
print("LED is on")
elif data=="off":
print("LED is off")
else:
break
conn.close()
server_soc.close()
(客户)
import socket
mysoc=socket.socket()
mysoc.connect(("127.0.0.1",1234))
s=""
while s!="exit":
s=input("Enter command")
mysoc.sendall(s.encode('utf-8'))
mysoc.close()
(我删除了所有与LED相关的命令,以便能够在计算机中运行脚本,您必须将它们再次添加到代码中。)