gpt4 book ai didi

python - python扭曲中的多组聊天服务器

转载 作者:太空宇宙 更新时间:2023-11-03 18:20:12 24 4
gpt4 key购买 nike

我正在使用twisted框架运行一个聊天服务器,它非常适合一个组,但我需要多个组,以便用户可以加入特定组,并且他可以向该特定组发送/接收消息,那么如何创建多个组或工作函数“joinroom(self,roomname)”并且用户将被重定向到该组?

from twisted.internet import reactor,protocol                                           
from twisted.protocols import basic
from twisted.internet.protocol import Protocol, ClientFactory
import time

def t():

return "["+ time.strftime("%H:%M:%S") +"] "

class EchoProtocol(basic.LineReceiver):
name = "Unnamed"

def connectionMade(self):

self.transport.write("WhiteNOISE"+"\n")
self.sendLine("Enter A name Below...")
self.sendLine("")
self.count = 0
self.factory.clients.append(self)
self.factory.group.append(self)
print t() + "+ Connection from: "+ self.transport.getPeer().host

def connectionLost(self, reason):

self.sendMsg("- %s left." % self.name)
print t() + "- Connection lost: "+ self.name
self.factory.clients.remove(self)
def dataReceived(self, data):
#print "data is ", data
a = data.split(':')
if len(a) > 1:
command = a[0]
content = a[1]


msg = ""
if command == "iam":
self.name = content
msg = self.name + " has joined"

elif command == "msg":
msg = self.name + ": " + content
elif command == "quit":
self.transport.loseConnection()
return
elif command == "/ul":
self.chatters()
return()

print msg
self.sendMsg(msg)

def username(self, line):

for x in self.factory.clients:
if x.name == line:
self.sendLine("This username is taken; please choose another")
return

self.name = line
self.chatters()
self.sendLine("You have been connected!")
self.sendLine("")
self.count += 1
self.sendMsg("+ %s joined." % self.name)
print '%s~ %s connected as: %s' % (t(), self.transport.getPeer().host, self.name)

def chatters(self):
x = len(self.factory.clients) - 1
s = 'is' if x == 1 else 'are'
p = 'person' if x == 1 else 'people'
self.sendLine("There %s %i other %s connected:" % (s, x, p) )

for client in self.factory.clients:
if client is not self:
self.sendLine(client.name)
self.sendLine("")

def sendMsg(self, message):

for client in self.factory.clients:
client.transport.write( message + '\n')



class EchoServerFactory(protocol.ClientFactory):
protocol = EchoProtocol
clients = []

if __name__ == "__main__":
reactor.listenTCP(5001, EchoServerFactory())
print "Chat Server Started"
reactor.run()

最佳答案

这是一些伪代码,我看到您已经在工厂中创建了名为 group 的变量,所以我猜您有类似的想法,但尝试使用字典而不是列表,以便您可以更优雅地命名和访问您的组。

当然,这意味着您的“msg”命令应该指定组,以便您知道将消息发送到哪个组。

class EchoServerFactory(protocol.ClientFactory):                                         
protocol = EchoProtocol
clients = []
groups = {}

def dataReceived(self, data):
# Split string ,error checking ...
if command == "join":
self.factory.groups.get(content, []).append(self)
# handle other commands

def sendMsg(self, message, group):
for client in self.factory.groups[group]:
client.transport.write( message + '\n')

这确实是微不足道的,例如,没有回滚功能,因此新客户将看不到聊天历史记录,消息传递不可靠,因为您不使用任何类型的确认来向服务器发出信号,表明客户端确实已收到消息,或者服务器应将消息重新发送给某些客户端。

更好、更强大的解决方案可能包括:

  • 使用Twisted IRC server protocol
  • 使用TwistedWords即时通讯服务器/客户端(简单)
  • Redis PubSub轻松地将消息从单个客户端扇出到在同一 channel 上订阅的所有其他客户端(不可靠,实现起来几乎微不足道)
  • 使用 RabbitMQ将消息路由到所需的客户端或其他一些消息代理(可靠、健壮,比 Redis 或 TwistedWords 需要更多设置)

这是对 reliable and unreliable 含义的简短解释。 .

Reliable messaging is the concept of communicating messages across an unreliable infrastructure whilst being able to make certain guarantees about the successful transmission of the messages; for example, that if the message is delivered, it is delivered at most once, or that all messages successfully delivered arrive in a particular order.

免责声明:我只是提出了我过去使用过的技术和想法,可能还有数百种方法来实现[简单,强大]群聊。

关于python - python扭曲中的多组聊天服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24284548/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com