Python 套接字在使用 pygame 时只接收一次输入
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 文档中提取了服务器代码和客户端发送代码。)
我正在尝试使用依赖于箭头键状态的套接字发送消息,似乎第一个按键工作正常,然后其余的都无关紧要。
客户代码:
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 文档中提取了服务器代码和客户端发送代码。)