将select.select与pygame

时间:2018-03-20 16:10:36

标签: python select pygame

您好我正在尝试创建一个基本的pygame客户端,它应该能够在运行时发送消息,我真的不确定如何连接select.select和pygame(和我不想使用线程)。 这是我的客户端代码,似乎select.select行阻止了pygame窗口:

import pygame
import socket
import select


messages_to_send = []
open_client_sockets = []


def send_waiting_messages(wlist):
    for message in messages_to_send:
        (client_socket, data) = message
        if client_socket in wlist:
            client_socket.send(data)
            messages_to_send.remove(message)


def display(str):

        text = font.render(str, True, (255, 255, 255), (159, 182, 205))
        textRect = text.get_rect()
        textRect.centerx = screen.get_rect().centerx
        textRect.centery = screen.get_rect().centery

        screen.blit(text, textRect)
        pygame.display.update()

pygame.init()
screen = pygame.display.set_mode( (640,480) )
pygame.display.set_caption('Python numbers')
screen.fill((159, 182, 205))

font = pygame.font.Font(None, 17)
num = 0
done = False
my_socket = socket.socket()
my_socket.connect(('127.0.0.1', 57))
while not done:
        display(str(num))
        num += 1
        rlist, wlist, xlist = select.select([my_socket] + open_client_sockets, open_client_sockets, [])
        for current_socket in rlist:
            if current_socket is my_socket:
                (new_socket, address) = my_socket.accept()
                open_client_sockets.append(new_socket)
            else:
                pygame.event.pump()
                keys = pygame.key.get_pressed()
                if keys[pygame.K_ESCAPE] is False:
                    open_client_sockets.remove(current_socket)
                    print 'Connection with client closed'
                else:
                    messages_to_send.append((current_socket, 'Hello, '))

        send_waiting_messages(wlist)

1 个答案:

答案 0 :(得分:1)

这是我如何修改主循环以包含超时。

while not done:
    display(str(num))
    num += 1
    rlist, wlist, xlist = select.select([my_socket] + open_client_sockets, open_client_sockets, [], 0.1)
    if not rlist: # a timeout occurred
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                print("Exiting!")
                done = True
    else:
        for current_socket in rlist:
            if current_socket is my_socket:
                (new_socket, address) = my_socket.accept()
                open_client_sockets.append(new_socket)
            else:
                keys = pygame.key.get_pressed()
                if keys[pygame.K_ESCAPE] is False:
                    open_client_sockets.remove(current_socket)
                    print('Connection with client closed')
                else:  # send Hello on any other key press
                    messages_to_send.append((current_socket, 'Hello, '))
    send_waiting_messages(wlist)