我在客户端和服务器之间建立了套接字连接。我能够连接并发送数据,但它会不断重复相同的数据,而不是在读取一行后停止/暂停。
预期输出:
Reading: ls /home
实际输出:Reading: ls /homeReading: ls /homeReading: ls /homeReading: ls /homeReading: ls /homeReading: ls /homeReading: ls /homeReading: ls /homeReading: ls /homeReading: ls /homeReading: ls /homeReading: ls /homeReading: ls /homeReading: ls /homeReading: ls /homeReading: ls /homeReading: ls /homeReading: ls /homeReading: ls /homeReading: ls /homeReading: ls /homeReading: ls /homeReading: ls /home...
客户代码:import socket
import sys
readOut = 0 # serial data
ipaddr = 'localhost'
ipport = 666
#def hitsocket(ipaddr):
#with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
print ("Starting up")
connected = False
class LineReader:
def __init__(self, socket, encoding='ascii'):
self.s = socket
self.encoding = encoding
self.buf = b''
self.closed = False
def readline(self):
while True:
index = self.buf.find(b'\n')
if index >= 0:
line = self.buf[:index+1]
self.buf = self.buf[index+1:]
return line.decode(self.encoding)
if self.closed:
line = self.buf
self.buf = b''
return line.decode(self.encoding)
data = self.s.recv(1024)
self.closed = len(data) == 0
print("raw recv:", data)
self.buf += data
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
try:
s.connect((ipaddr , ipport))
reader = LineReader(s)
while True:
line = reader.readline()
while(line):
if not line:
break
print(f"Reading: {line}", end='')
if "Fahrenheit" in line:
cread = line[22:-2]
newcread = float(cread)
print("cread ", cread,
"newcread ", newcread)
finally:
print('closing socket', file=sys.stderr)
s.close()
服务器代码:import socket
import time
inputdata = input("Enter command: ")
test_data = bytes(inputdata, encoding='utf-8')
s = socket.socket()
# todo: change as needed, but must match address in client script
s.bind(('localhost', 666))
s.listen()
while True:
c, addr = s.accept()
# send in framents to test reassembler
try:
if(test_data):
c.send(test_data)
except Exception as e:
print(e)
time.sleep(.1)
c.shutdown(socket.SHUT_RDWR)
c.close()
如何获得套接字连接以读取单行输入并等待下一行?
最佳答案
在您的客户端代码的以下块中,line
的值在您最里面的while循环中始终不变。并且由于其为非空字符串,因此循环条件始终为true,我认为使用if更改while
可能会有所帮助。
之后,您也不需要if not line
条件,我想您是在尝试解决问题时添加的。
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
try:
s.connect((ipaddr , ipport))
reader = LineReader(s)
while True:
line = reader.readline()
if line:
print(f"Reading: {line}", end='')
if "Fahrenheit" in line:
cread = line[22:-2]
newcread = float(cread)
print("cread ", cread,
"newcread ", newcread)
finally:
print('closing socket', file=sys.stderr)
s.close()
关于python - 如何不重复发送数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66271967/