zoukankan      html  css  js  c++  java
  • python使用twisted搭建的一个socket服务

    服务端

    # -*- coding: utf-8 -*-
    # @Time : 2018/9/19 21:41
    # @Author : cxa
    # @File : tsTservTW.py
    # @Software: PyCharm
    '''
    Twisted Reactor时间戳TCP服务器
    '''
    from twisted.internet import protocol, reactor
    from time import ctime
    import msgpack
    
    PORT = 21567
    
    
    class TSServProtocol(protocol.Protocol):
        def connectionMade(self):
            '''
            当客户端连接的时候会执行该方法
            :return:
            '''
            clnt = self.clnt = self.transport.getPeer().host
            print(f"...来自的{clnt}链接:")
    
        def dataReceived(self, data):
            '''
            接收到客户端的数据
            :param data:
            :return:
            '''
            print(f"来自客户端:{msgpack.unpackb(data,encoding='utf')}")
            data = f"{ctime()}:来自服务器:你好"
            self.transport.write(msgpack.packb(data))
    
    
    if __name__ == '__main__':
        # 创建一个协议工厂,之所以称之为工厂是因为,每次得到一个
        # 接入连接时,都能"制造"协议的一个实例。
        factory = protocol.Factory()
    
        factory.protocol = TSServProtocol
        print("....等待链接..")
        # 使用reactor安装一个TCP监听器,检查服务请求。
        # 当它接收到一个请求时,就会创建一个TSServProtocol实例来处理那个客户端的事务。
        reactor.listenTCP(PORT, factory)
        reactor.run()
    
    

    客户端

    # -*- coding: utf-8 -*-
    # @Time : 2018/9/19 21:57
    # @Author : cxa
    # @File : tsTclntTW.py
    # @Software: PyCharm
    '''
    创建Twisted Reactor TCP客户端
    '''
    from twisted.internet import protocol, reactor
    import msgpack
    
    HOST = 'localhost'
    PORT = 21567
    
    
    class TSClntProtocol(protocol.Protocol):
        def sendData(self):
            data = input('>')
            if data:
                print(f'...发送数据 {data}')
                self.transport.write(msgpack.packb(data))
            else:
                self.transport.loseConnection()
    
        def connectionMade(self):
            self.sendData()
    
        def dataReceived(self, data):
            print(msgpack.unpackb(data, encoding="utf8"))
            self.sendData()
    
    
    class TSClntFactory(protocol.ClientFactory):
        protocol = TSClntProtocol
        clientConnctionLost = clientConnctionFailed = lambda self, connector, reason: reactor.stop()
    
    
    if __name__ == '__main__':
        reactor.connectTCP(HOST, PORT, TSClntFactory())
        reactor.run()
    
    
  • 相关阅读:
    LINQ to SQL语句(9)之Top/Bottom和Paging和SqlMethods
    LINQ to SQL语句(8)之Concat/Union/Intersect/Except
    LINQ to SQL语句(7)之Exists/In/Any/All/Contains
    LINQ to SQL语句(6)之Group By/Having
    LINQ to SQL语句(5)之Order By
    LINQ to SQL语句(4)之Join
    LINQ to SQL语句(3)之Count/Sum/Min/Max/Avg
    LINQ to SQL语句(2)之Select/Distinct
    java 开发工具记录
    H5播放器内置播放视频(兼容绝大多数安卓和ios)
  • 原文地址:https://www.cnblogs.com/c-x-a/p/9678315.html
Copyright © 2011-2022 走看看