如何优化我的“线程UDP服务器”

时间:2016-04-05 13:42:37

标签: python multiplayer socketserver

我正在制作一款多人平台游戏,一旦我连接了大约7个以上的客户端,目前就存在服务器性能问题。上周早些时候我被告知我应该调查socketserver,因为之前我只使用socket编写自己的服务器。

好吧,经过6个小时的实施,我的服务器正在使用新代码。

目前看来,我没有看到性能提升,但这并不奇怪。我希望有人能指出我正确的方向,并告诉我如何从这件事中获得更多的表现。

服务器目前有600行代码,但我认为瓶颈是socketserver

所以这是(希望)相关的东西。 和往常一样......非常感谢你:)

import socket
import sys
import threading
import time
import pygame
import random
import json
import levels
import socketserver

class MyUDPHandler(socketserver.BaseRequestHandler):
    def handle(self):
        data = self.request[0].strip()
        socket = self.request[1]
        gameserver.listen(data, self.client_address)

class ThreadingUDPServer(socketserver.ThreadingMixIn, socketserver.UDPServer):
    pass

class GameServer():
    def __init__(self):
        self.message_count = 100000
        self.message_dump = None
        self.text_block = []
        self.client_list = []
        self.client_hero_dict = {}
        self.client_obj_dict = {}
        self.queue = []

    def listen(self, data, addr):
        if addr not in self.client_list:
            Client(addr, self.dataHandler(data)) #Makes a client object for future reference
            print("Accepted connection: " + repr(addr))
            print("List of all connections: " + repr(self.client_list))

            for line in servermap.map: #This sends the map to the newly connected client
                line = "TILE" + line
                threading.Thread(target=self.clientHandler(line, addr))
            for obj in identifier.object_dict:
                threading.Thread(target=self.clientHandler(identifier.object_dict[obj]))
        self.dataHandler(data, addr)

    def textHandler(self, data):
        if data:
            data = "^^%s^^" % str(self.message_count) + data
            self.message_count += 1
            threading.Thread(target=self.clientHandler(data))

    def dataHandler(self, data, addr=None):
        data = data.decode()
        if data[0:2] == "^^": # if data is a chat message
            self.textHandler(data[2:])
        if data[0:2] == "*^": # if data is a movement request
            self.client_hero_dict[addr].actionfsm(data[2:])
        if data[0:6] == "**UN**": #if data is a username
            # self.client_obj_dict[addr] = data[6:]
            return data[6:]
            # self.client_hero_dict[addr].name = data[6:]
            # print(self.client_hero_dict[addr].name + " is the Username for " + repr(str(addr)))


    def clientHandler(self, message_to_send, specific_client=None):
        if type(message_to_send) == dict: #I use dictionaries as simple ways to send object (player/sprite) update information
                message_to_send = json.dumps(message_to_send)
        if specific_client:
            server.socket.sendto(message_to_send.encode(), specific_client)
        else:
            for client in self.client_list:
                server.socket.sendto(message_to_send.encode(), client)

0 个答案:

没有答案