我试图使用依赖于我的箭头键状态的套接字发送消息,似乎第一个按键工作正常,然后其余的是无关紧要的。
客户代码:
导入套接字进口……
它只能工作一次,因为您只创建一个到服务器的连接。 (在客户端代码的第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文档中删除了服务器代码和客户端发送代码。)
套接字文档
socketserver文档