python - 当客户端尝试与扭曲的聊天服务器通信时,出现未处理的错误并且连接丢失

标签 python twisted twisted.internet

from twisted.internet.protocol import Protocol,Factory
from twisted.internet import reactor

class ChatServer(Protocol):
def connectionMade(self):
    print "A Client Has Connected"
    self.factory.clients.append(self)
    print"clients are ",self.factory.clients
    self.transport.write('Hello,Welcome to the telnet chat to sign in type aim:YOUR NAME HERE to send a messsage type msg:YOURMESSAGE '+'\n')

def connectionLost(self,reason):
    self.factory.clients.remove(self)
    self.transport.write('Somebody was disconnected from the server')

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 + "has joined"

    elif command == "msg":
    ma=sg = self.name + ":" +content

    print msg
    for c in self.factory.clients:
        c.message(msg)
def message(self,message):
    self.transport.write(message + '\n')

factory = Factory()
factory.protocol = ChatServer
factory.clients = []
reactor.listenTCP(80,factory)
print "Iphone Chat server started"
reactor.run()

上面的代码运行成功...但是当我将客户端(通过输入 telnet localhost 80)连接到该聊天服务器并尝试写入消息时,连接丢失并发生以下错误:

Iphone Chat server started
A Client Has Connected
clients are [<__main__.ChatServer instance at 0x024AC0A8>]
Unhandled Error
Traceback (most recent call last):
File "C:\Python27\lib\site-packages\twisted\python\log.py", line 84, in callWithLogger
return callWithContext({"system": lp}, func, *args, **kw)
File "C:\Python27\lib\site-packages\twisted\python\log.py", line 69, in callWithContext
return context.call({ILogContext: newCtx}, func, *args, **kw)
File "C:\Python27\lib\site-packages\twisted\python\context.py", line 118, in callWithContext
return self.currentContext().callWithContext(ctx, func, *args, **kw)
File "C:\Python27\lib\site-packages\twisted\python\context.py", line 81, in callWithContext
return func(*args,**kw)
--- ---
File "C:\Python27\lib\site-packages\twisted\internet\selectreactor.py", line 150, in _doReadOrWrite
why = getattr(selectable, method)()
File "C:\Python27\lib\site-packages\twisted\internet\tcp.py", line 199, in doRead
rval = self.protocol.dataReceived(data)
File "D:\chatserverultimate.py", line 21, in dataReceived
content = a[1]
exceptions.IndexError: list index out of range

我哪里出错了?

最佳答案

您错误地缩进了 content = a[1] 行。您需要更多空间! :)

关于python - 当客户端尝试与扭曲的聊天服务器通信时,出现未处理的错误并且连接丢失,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17382218/

相关文章:

python - 如何知道 reactor 在 python 中是否正在运行?

python - twisted.internet.reactor.spawnProcess 引发 OSError(13, 'Permission denied')

python - 多处理池 - 如果返回所需结果,如何取消所有正在运行的进程?

python - 将绘图中的数据保存到 numpy 数组

python - 装饰 DBUS 方法

python - 了解 Twisted 和异步编程。为什么一段代码有效而另一段代码无效?

python - Sphinx automodule 不愿意导入翻译

python - 我可以使用Python将内存中的对象上传到FTP吗?

python - 扭曲的框架需要一些澄清

java - 在 Java 客户端和 Twisted Python 套接字服务器之间发送缓冲图像