socket.error: [Errno 10061]
表示您尝试连接的端口未打开。您需要确保端口已打开,并且正在侦听您的连接。
您似乎正在尝试测试聊天服务器。为了让聊天服务器正常工作,您需要确保它当前正在侦听指定端口。
如果您以前没有检查过Twisted ,它提供了一个很好的框架。
from twisted.internet.protocol import Factory
from twisted.protocols.basic import LineReceiver
from twisted.internet import reactor
class Chat(LineReceiver):
def __init__(self, users):
self.users = users
self.name = None
self.state = "GETNAME"
def connectionMade(self):
self.sendLine("What's your name?")
def connectionLost(self, reason):
if self.users.has_key(self.name):
del self.users[self.name]
def lineReceived(self, line):
if self.state == "GETNAME":
self.handle_GETNAME(line)
else:
self.handle_CHAT(line)
def handle_GETNAME(self, name):
if self.users.has_key(name):
self.sendLine("Name taken, please choose another.")
return
self.sendLine("Welcome, %s!" % (name,))
self.name = name
self.users[name] = self
self.state = "CHAT"
def handle_CHAT(self, message):
message = "<%s> %s" % (self.name, message)
for name, protocol in self.users.iteritems():
if ':' in message:
self.exc(message.split(':')[0])
if protocol != self:
protocol.sendLine(message)
def exc(self, cmd):
print cmd
if cmd == 'who':
for i in self.users:
print i
class ChatFactory(Factory):
def __init__(self):
self.users = {} # maps user names to Chat instances
def buildProtocol(self, addr):
return Chat(self.users)
reactor.listenTCP(8123, ChatFactory())
reactor.run()