我正在尝试编写一个简单的多人类型文本游戏。我现在有一个简单的聊天服务器。它正如它应该的那样工作,将信息回应给所有相关人员。
我无法弄清楚如何迈出下一步。我想关联连接到播放器对象的客户端。播放器对象包含有人可以输入的可用命令,因此为了继续解析输入,我必须能够做到这一点 - 我只是不知道如何。
目前,玩家对象只是一个标准对象类,其中包含一些属性,如“name”,“id”,“location”,它们具有可用的命令列表。如果您需要一个代码示例,我可以提供一个。
有什么想法吗?
import socket, select
from helpers.colorize import colorize
class Server(object):
def __init__(self, host, port):
self.server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self.server.bind((host, port))
self.server.listen(1)
self.clients = [self.server]
def start(self):
while True:
read_sockets,write_sockets,error_sockets = select.select(self.clients, [], [])
for sock in read_sockets:
#new conn
if sock == self.server:
sockfd, addr = self.server.accept()
self.clients.append(sockfd)
print "Connection from %s %s" % addr
#looks like a message
else:
#data recieved, lets try and do something
try:
data = sock.recv(4096)
if data: #we have something, parse it
self.sendall(sock, data) #give it to everyone for now
except: #disconnection, remove from our lists
self.sendall(sock, ("%s %s disconnected" % addr))
print "%s %s disconnected." % addr
socket.close()
self.clients.remove(sock)
continue
self.server.close()
def send(self, sock, message):
sock.send(colorize(message))
def sendall(self, sock, message):
#Do not send the message to master socket and the client who has send us the message
for socket in self.clients:
if socket != self.server:
try :
socket.send(message)
except :
# broken socket connection may be, chat client pressed ctrl+c for example
socket.close()
CONNECTION_LIST.remove(socket)
if __name__ == "__main__":
s = Server('localhost', 2222)
s.start()