python连接输入_在侦听Python中的连接时接收命令行输入

I am trying to write a program that has clients connect to it while the server is still able to send commands to all of the clients. I am using the "Twisted" solution. How can I go about this? Here is the code I have so far (I understand that Twisted already uses non-blocking sockets):

import threading

print 'threading.'

def dock():

try:

from twisted.internet.protocol import Factory, Protocol

from twisted.internet import reactor

import currentTime

print '[*]Imports succesful.'

except:

print '[/]Imports failed.'

#Define the class for the protocol

class Master(Protocol):

command = raw_input('> ')

def connectionMade(self):

print 'Slave connected.'

print currentTime.getTime() #Print current time

#self.transport.write("Hello")

def connectionLost(self, reason):

print 'Lost.'

#Assemble it in a "factory"

class MasterFactory(Factory):

protocol = Master

reactor.listenTCP(8800, MasterFactory())

#Run it all

reactor.run()

def commandline():

raw_input('>')

threading.Thread(target=dock()).start()

threading.Thread(target=commandline()).start()

解决方案

Since you're already using twisted, you should also use it for the console part, instead of using raw_input in a thread.

Twisted's event loop can monitor any file descriptor for changes, including the standard input, so you can get event-based callbacks on a new line entered -- It works asynchronously without need for threads.

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值