Python Twisted Socket Server client

Source: Internet
Author: User

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.