以下Python代码在两台计算机之间打开TCP连接,传输短字符串消息,然后终止连接。但是由于某种原因,数据无法通过。连接似乎正常,但数据未通过。我在做什么错了?
服务器:
#! /usr/bin/python3
import socket
import sys
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_address = (IP, 10000)
sock.bind(server_address)
sock.listen(1)
print('starting up on %s port %s' % server_address)
while True:
# Wait for a connection
print('waiting for a connection')
connection, client_address = sock.accept()
try:
while True:
data = connection.recv(28)
print('received "%s"' % data)
if data:
print(data)
else:
print('no more data from', client_address)
break
finally:
# Clean up the connection
connection.close()
客户:
def Data_Out(Status):
Exists = os.path.exists('/run/thermostat/outsideIP')
if Exists:
with open("/run/thermostat/outsideIP", "r") as f:
IP = f.read()
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# Connect the socket to the port on the server
server_address = (IP, 10000)
try:
socket.create_connection(server_address, timeout=10)
except socket.timeout as err:
return err
if Status == 0:
message = '[1, 0, 0, 1, 1, 1, 1, 1]\n'
elif Status == 1:
message = '[0, 1, 0, 1, 1, 1, 1, 1]\n'
else:
message = '[0, 0, 0, 0, 0, 0, 0, 0]\n'
try:
sock.sendall(message)
finally:
sock.close()
return 0
else:
return -1
服务器响应:
HVAC-Relay1:/usr/local/sbin# TClient.py
starting up on 192.168.1.34 port 10000
waiting for a connection
received "b''"
no more data from ('192.168.1.28', 46380)
waiting for a connection
客户响应:
pi@Thermostat-Office:/usr/local/sbin $ DISPLAY=:0 Relay_Sync.py
0
答案 0 :(得分:0)
问题是套接字需要字节流,而不是字符串:
import pickle
data = pickle.dumps(message)
sock.sendall(data)