Using twisted to build a socket server, and can send messages to the client, relatively simple, directly on the code
#coding =utf-8
‘‘‘
Used to implement a request to the response client, and can send a message to the customer,
‘‘‘
fromTwisted.internetImportReactor
fromTwisted.internet.protocolImportProtocol, Factory
ImportTime
ImportThread
#线程体,
defTimerNo, interval):
whileTrue:
Time.sleep (interval)
Print(Time.strftime ('%y-%m-%d%h:%m:%s ', Time.localtime (Time.time ())))
forElementIn MyFactory.clients:
Print(Element) #在这里可以给每个客户端发送消息
Element.transport.getHandle (). Sendall (' dddddddddddd ')
Thread.exit_thread ()
class MyProtocal (Protocol):
defConnectionmade ( Self):
Self. Factory.addclient ( Self)
defConnectionlost ( Self, reason):
#print (reason)
Self. Factory.deleteclient ( Self)
defDataReceived ( Self, data):
Self. Transport.write (' okthis is ok ') #在这里接收用户的请求认证, and return data, send data using Transport.gethandle (). Sendall () Ensure data is sent to the client immediately
class MyFactory (Factory):
protocol = myprotocal
Clients=[] #用户保存客户端列表,
def__init__( Self):
Thread.start_new_thread (Timer, (1,3))
#启动线程用于处理用于给客户端主动发送数据
defAddclient ( Self, newclient):
Print(newclient)
Self. Clients.append (Newclient)
defDeleteclient ( Self, client):
Print(client)
Self. Clients.remove (client)
REACTOR.LISTENTCP (9999, MyFactory ())
Reactor.run ()
This can be done on the basis of many of the functions of the module.
There are the following doubts about how I can control the stop server through code. (How to use Reactor.stop ())
Python Twisted Socket Server client