繁体   English   中英

使用pygame时,Python套接字仅接收一次输入

[英]Python socket only receives input once when using pygame

我试图使用套接字发送消息,具体取决于我的箭头键的状态,看来第一次按键工作正常,然后其余的都无关紧要。

客户代码:

import socket
import pygame
sender = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
host = '127.0.0.1' #loop back
port = 59769
sender.connect((host,port))
pygame.init()
pygame.display.set_mode((40,40))


while True:
    for event in pygame.event.get():
        if event.type == pygame.KEYDOWN and event.key == pygame.K_LEFT:
            sender.send("2".encode())
        if event.type == pygame.KEYDOWN and event.key == pygame.K_RIGHT:
            sender.send("3".encode())
        if event.type == pygame.KEYDOWN and event.key == pygame.K_UP:
            sender.send("1".encode())
        if event.type == pygame.KEYDOWN and event.key == pygame.K_DOWN:
            sender.send("2".encode())
    pygame.event.pump()
    pygame.display.update()

服务器代码

import socket
import atexit

#Setup socket
PORT = 59769 #Choose any open port, alternatively choose one in advance
HOST = '0.0.0.0' #listen from any device

serversocket = socket.socket()
serversocket.bind((HOST,PORT))
def exit_handler():
    print("Handling exit...")
    serversocket.close()

print("Socket created at port " + str(serversocket.getsockname()[1]))
#How many devices to listen to
serversocket.listen(1)

#Wait for input
while True:
    connection,address = serversocket.accept()
    received= connection.recv(1024).decode()
    print(received)
    #print("Brightness being set to "+received)
    #print("Brightness succesfully set")

为什么它只能工作一次,我该如何解决?

它只能工作一次,因为您只能创建到服务器的一个连接。 (在客户代码的第6行。)您需要为每个请求创建一个新的连接。

客户代码:

import socket
import pygame
host = 'localhost' #loop back
port = 59769
pygame.init()
pygame.display.set_mode((250, 250))


def send(data):
    # Create a socket (SOCK_STREAM means a TCP socket)
    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
        # Connect to server and send data
        sock.connect((host, port))
        sock.sendall(bytes(data + "\n", "utf-8"))


while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            exit()

        if event.type == pygame.KEYDOWN and event.key == pygame.K_LEFT:
            send('2')
        if event.type == pygame.KEYDOWN and event.key == pygame.K_RIGHT:
            send('3')
        if event.type == pygame.KEYDOWN and event.key == pygame.K_UP:
            send('1')
        if event.type == pygame.KEYDOWN and event.key == pygame.K_DOWN:
            send('2')

    pygame.display.update()

服务器代码:

import socketserver

class MyTCPHandler(socketserver.BaseRequestHandler):
    """
    The request handler class for our server.

    It is instantiated once per connection to the server, and must
    override the handle() method to implement communication to the
    client.
    """

    def handle(self):
        # self.request is the TCP socket connected to the client
        self.data = self.request.recv(1024).strip()
        print(self.data.decode())

if __name__ == "__main__":
    HOST, PORT = "0.0.0.0", 59769

    # Create the server, binding to localhost on port 9999
    with socketserver.TCPServer((HOST, PORT), MyTCPHandler) as server:
        # Activate the server; this will keep running until you
        # interrupt the program with Ctrl-C
        server.serve_forever()

更多信息:(我直接从socketserver文档中剥离了​​服务器代码和客户端发送代码。)

套接字文档

套接字服务器文档

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM