python - 如何不重复发送数据?

标签 python python-3.x sockets

我在客户端和服务器之间建立了套接字连接。我能够连接并发送数据,但它会不断重复相同的数据,而不是在读取一行后停止/暂停。
预期输出:

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/

相关文章:

python - 减少 multiprocessing.Pool.starmap() 列表的内存大小

python - 如何将 FOPDT 模型的死区时间应用于 MPC gekko 中的操纵变量

python - Tkinter 小部件之间的空间不断增长

django - 如何在 Heroku 上的 Django 中保存日志文件

python - 如何绘制股票数据的滚动平均值?

Python 3.1-网格模拟概念问题

c - 未使用 MinGW 编译的 Winsock 服务器代码

java - 如果套接字已打开,则强制关闭该套接字

java - 为什么来自多个套接字的输入无法正确更新 UI?

python - Peewee 插入如果不存在