Python - 套接字服务器接收的数据多于我发送的数据

时间:2017-03-19 19:51:12

标签: python sockets

当我倾斜手机时,我发了一个应用程序向python socket发送消息“Oleft”,但控制台上的结果如下:

  

('192.168.0.101',33313)的连接   b'Oleft“
  b'OleftOleftOleftOleftOleftOleftOleftOleftOleftOleftOleft“
  b'Oleft“
  b'OrightOrightOrightOright“
  b'OleftOleftOleftOleftOleftOrightOrightOrightOrightOrightOrightOleftOleftOleftOleftOleftOleftOleftOleftOleftOleftOleftOleftOleftOleftOleftOleftOleftOleftOleftOleft“
  b'OleftOleftOleftOleftOleftOleftOleftOleftOleftOleftOleft“
  b'OleftOleftOleftOleftOleftOleftOleftOleftOleftOleftOleft“
  b'OleftOleftOleftOleftOleftOleftOleftOleftOleftOleftOleft“
  b'OleftOleft'

它无法只收到b'Oleft'?

wgremote.py

import socket

class WGRemote:

    def __init__(self):
        self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.host = socket.gethostname()
        self.port = 10000
        self.received = None

    def connect(self):
        global c, addr
        self.sock.bind((self.host, self.port))
        self.sock.listen(5)
        c, addr = self.sock.accept()
        print('connection from' + str(addr))

    def setMode(self,mode):
        sent = c.send(mode.encode("utf-8"))

    def receive(self):
        self.received = c.recv(1024)
        return self.received

    def close(self):
        c.close

testApp.py

import socket
import sys
from wgremote import WGRemote

remote = WGRemote()
remote.connect()
remote.setMode('orient')
while True:
    data = remote.receive()
    print(data)

1 个答案:

答案 0 :(得分:0)

因为,你在while循环中写了print(data):)

while True:
    data = remote.receive()
    print(data)

如果您只想接收b'Oleft,可以制作过滤器:

count = 0
while True:
  data = remote.receive()
  if data == "b'Oleft":
    if count < 1:
      count = count + 1
      print(data)

或者你必须发送唯一的b'Oleft:)