SOCKET | PYTHON |如何一次接收一条消息(?)

时间:2018-05-04 12:49:56

标签: python multithreading sockets

所以我试图制作这个2人在线游戏,所以我编码将第一个客户端的蛇位置发送到服务器和服务器将该数据发送到第二个客户端并为第二个客户端执行相同操作。但是当客户收到头寸时,客户会获得多个头寸。 为了说清楚,我将用代码解释

all_sprite = pg.sprite.Group()

class Opponent(pg.sprite.Sprite):
    def __init__(self):
        self.group = all_sprite
        pg.sprite.Sprite.__init__(self, self.group)
        self.image = pg.Surface((TILESIZE, TILESIZE))
        self.image.fill((155,155,155))
        self.rect = self.image.get_rect()
tLock = threading.Lock()
#to recieve the data
def recv():
    while True:
        with tLock:
            data = str(sock.recv(1024), 'utf-8')
            try:
                a,b = map(int, data.split())
                print(a,b)
                o.rect.x = a
                o.rect.y = b
            except:
                if data == "ok":
                    o = Opponent()
                else:
                    print(data)

sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect(('127.0.0.1', 6666))

sThread = threading.Thread(target=recv)
sThread.daemon = True
sThread.start()  


# To send the data
class Sending(threading.Thread):
    def __init__(self,s):
        self.x = 0
        self.y = 0
        self.lock = threading.RLock()
        self.socket = s
        super(Sending, self).__init__()
    def setxny(self,x,y):
        with self.lock:
            self.x = x
            self.y = y
    def run(self):
        while True:
            with self.lock:
                a,b= str(self.x),str(self.y)
                self.socket.send(bytes(a+" "+b, 'utf-8'))
send_thread = Sending(sock)
send_thread.daemon=True
send_thread.start()

while RUNNING:
    send_thread.setxny(snakehead.rect.x,snakehead.rect.y )
    clock.tick(1)
    for event in pg.event.get():
if event.type == pg.QUIT:
            RUNNING = False
.....after this it's all about pygame so i will not include it

检查客户端是否正在接收正确的蛇位置,我编码在客户端收到数据时打印数据并且输出是

100 480100 480100 480100 480100 480100 480100 480100 480100 480100 480100 480100 480100 480100 480100 480100 480100 480100 480100 480100 480100 480100

这就是我想看到的......

100 480

我该如何解决这个问题?

0 个答案:

没有答案