【 声明:版权所有,欢迎转载,请勿用于商业用途。 联系信箱:feixiaoxing @163.com】
我不擅长写socket代码。一是用c写起来比较麻烦,二是自己平时也没有这方面的需求。等到自己真正想了解的时候,才发现自己在这方面确实有需要改进的地方。最近由于项目的原因需要写一些python代码,才发现在python下面开发socket是一件多么爽的事情。
对于大多数socket来说,用户其实只要关注三个事件就可以了。这分别是创建、删除、和收发数据。python中的twisted库正好可以帮助我们完成这么一个目标,实用起来也不麻烦。下面的代码来自twistedmatrix网站,我觉得挺不错的,贴在这里和大家分享一下。如果需要测试的话,直接telnet localhost 8123就可以了。
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.name in self.users:
            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 name in self.users:
            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 protocol != self:
                protocol.sendLine(message)
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()原文:http://blog.csdn.net/feixiaoxing/article/details/50499961