python套接字仅接收最后一行

时间:2019-07-18 17:59:17

标签: python-3.x

我正在使用下面提供的代码通过套接字检索一些数据。发出此代码后,它会打印所有结果,直到断点为止,尽管我只在断行之前就在意接收到的行,换句话说,倒数第二行。因此,我需要一些帮助以了解如何实现。

import socket
import time

socket.setdefaulttimeout(10)
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect(("192.168.50.102", 2102))


curIndex = "0"
while True:
    sending_data = 'get,trx,'+curIndex
    #print sending_data
    client.send(sending_data)
    data = client.recv(128)
    print data.encode('UTF-8')
    if data == "trx,notfound": break

    spdata = data.split(",")
    #print spdata[2] + 'kg' #Prints weight + kg

    if len(spdata) >= 3:
        curIndex = spdata[1]

    time.sleep(0.5)
client.close()

实际输出

trx,2,1.250,0.000,19-07-11 14:08:01
trx,3,0.500,0.000,19-07-11 14:19:24
trx,4,0.500,0.000,19-07-11 15:04:37
trx,5,0.250,0.000,19-07-11 15:05:31
trx,6,0.177,0.000,19-07-11 21:06:59
trx,7,0.108,0.000,19-07-12 14:54:00
trx,8,0.106,0.000,19-07-16 17:51:06
trx,9,0.106,0.000,19-07-16 17:54:24
trx,10,0.106,0.000,19-07-18 14:31:49
trx,11,0.171,0.000,19-07-18 14:51:31
trx,notfound

所需的输出 trx,11,0.171,0.000,19-07-18 14:51:31

2 个答案:

答案 0 :(得分:0)

请勿打印:保存。
替换:

print data.encode('UTF-8')
if data == "trx,notfound": break

通过

if data == "trx,notfound": break
last_data = data.encode('UTF-8')

然后,最后(如client.close()之后),您可以print last_data

答案 1 :(得分:0)

尝试

stateChanged(stateName: string) {
  this.cityOptions = this.cities.filter(city => city.state === stateName);
}

代替

<mat-form-field>
  <mat-label>States</mat-label>
  <mat-select (selectionChange)="stateChanged($event.value)">
    <mat-option value="" disabled>All</mat-option>
    <mat-option 
      *ngFor="let state of states" 
      [value]="state.name">
      {{ state.name }}
    </mat-option>
  </mat-select>
</mat-form-field>

<br>

<mat-form-field>
  <mat-label>Cities</mat-label>
  <mat-select>
    <mat-option value="" disabled>All</mat-option>
    <mat-option 
      *ngFor="let city of cityOptions" 
      [value]="city.name">
      {{ city.name }}
    </mat-option>
  </mat-select>
</mat-form-field>

示例

data_b = client.recv(1024)
while data_b:
    data_b = client_socket.recv(1024)
    data += data_b