python twisted socket 服务端 客户端

使用twisted搭建socket的服务器,并能给客户端发送消息, 比较简单,直接上代码

#coding=utf-8

'''
用于实现给响应客户端的请求,并且可以给客户发送消息,
'''

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

#线程体,
def timer(no, interval):
   while True:
       time.sleep(interval)
       print(time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time())))
       for element in MyFactory.clients:
           print(element) #在这里可以给每个客户端发送消息
           element.transport.getHandle().sendall('dddddddddddd')
   thread.exit_thread()


class MyProtocal(Protocol):
   def connectionMade(self):
       self.factory.addClient(self)

   def connectionLost(self, reason):
       #print(reason)
       
self.factory.deleteClient(self)

   def dataReceived(self, data):
       self.transport.write('okthis is ok ') #在这里接收用户的请求认证,并返回数据,发送数据请使用transport.getHandle().sendall() 保证数据立刻发送到客户端

class MyFactory(Factory):

   protocol = MyProtocal
   clients=[] #用户保存客户端列表,

   def __init__(self):
       thread.start_new_thread(timer,(1,3))
       #启动线程用于处理用于给客户端主动发送数据

   def addClient(self, newclient):
       print(newclient)
       self.clients.append(newclient)

   def deleteClient(self, client):
       print(client)
       self.clients.remove(client)

reactor.listenTCP(9999, MyFactory())
reactor.run()

可以在此基础上完成很多模块的功能。 

存在以下疑惑点,我如何通过代码来控制停止服务器。 (如何使用reactor.stop())

=========================================

使用reactor.callLater()启动一个线程.线程里进行阻塞,或过虑按钮事件(hook)来调用reactor.stop()

转载于:https://my.oschina.net/u/198124/blog/466216

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值