Python网络编程:asynchat握手
我正在用Python的asynchat库来实现一个网络协议。在连接的时候,我需要发送一个命令,然后服务器会回复我一个会话。
我遇到的主要问题是,我需要等到收到会话的回复,但我不太确定该怎么做。是不是应该在连接设置的时候用socket.recv?这样做合适吗?
1 个回答
3
在用异步技术编写网络应用时,你需要通过记录你的状态来“等待”,然后让主循环继续运行。过一段时间后,你等待的数据会变得可用,主循环会通知你这个消息,然后你可以把新数据和记录的状态结合起来,完成你正在做的任务。根据具体的任务,你可能需要多次经历这个过程,才能真正完成你的工作。
这些想法基本上是相同的,不管你使用的是哪种异步系统。不过,Twisted 是一种比 asynchat 更优秀的系统,所以我不打算解释 asynchat 的细节。相反,这里有一个使用 Twisted 的例子,展示了你所询问的那种操作:
from twisted.internet.defer import Deferred
from twisted.internet.protocol import Protocol, Factory
from twisted.internet.endpoints import TCP4ClientEndpoint
from twisted.internet import reactor
# Stream-oriented connections like TCP are handled by an instance
# of a Protocol subclass
class SomeKindOfClient(Protocol):
# When a new connection is established, the first thing that
# happens is this method is called.
def connectionMade(self):
# self.transport is set by the superclass, and lets us
# send data over the connection
self.transport.write("GREETING")
# a Deferred is a generic, composable API for specifying
# callbacks
self.greetingComplete = Deferred()
# Here's some local state
self._buffer = ""
# Whenever bytes arrive on the TCP connection, they're passed
# to this method
def dataReceived(self, bytes):
# Incorportate the network event data into our local state.
# This kind of buffering is always necessary with TCP, because
# there's no guarantees about how many bytes will be delivered
# at once (except that it will be at least 1), regardless of
# the size of the send() the peer did.
self._buffer += bytes
# Figure out if we're done - let's say the server response is 32
# bytes of something
if len(self._buffer) >= 32:
# Deliver it to whomever is waiting, by way of the Deferred
# object
greeting, self._buffer = self._buffer[:32], self._buffer[32:]
complete = self.greetingComplete
self.greetingComplete = None
complete.callback(greeting)
# Otherwise we'll keep waiting until dataReceived is called again
# and we have enough bytes.
# One of the normal ways to create a new client connection
f = Factory()
f.protocol = SomeKindOfClient
e = TCP4ClientEndpoint(reactor, "somehost", 1234)
# Connect returns one of those Deferreds - letting us specify a function
# to call when the connection is established. The implementation of
# connect is also doing basically the same kind of thing as you're asking
# about.
d = e.connect(f)
# Execution continues to this point before the connection has been
# established. Define a function to use as a callback when the connection
# does get established.
def connected(proto):
# proto is an instance of SomeKindOfClient. It has the
# greetingComplete attribute, which we'll attach a callback to so we
# can "wait" for the greeting to be complete.
d = proto.greetingComplete
def gotGreeting(greeting):
# Note that this is really the core of the answer. This function
# is called *only* once the protocol has decided it has received
# some necessary data from the server. If you were waiting for a
# session identifier of some sort, this is where you might get it
# and be able to proceed with the remainder of your application
# logic.
print "Greeting arrived", repr(greeting)
# addCallback is how you hook a callback up to a Deferred - now
# gotGreeting will be called when d "fires" - ie, when its callback
# method is invoked by the dataReceived implementation above.
d.addCallback(gotGreeting)
# And do the same kind of thing to the Deferred we got from
# TCP4ClientEndpoint.connect
d.addCallback(connected)
# Start the main loop so network events can be processed
reactor.run()
要查看这个是如何工作的,你可以启动一个简单的服务器(比如 nc -l 1234
),然后让客户端连接到它。你会看到问候信息到达,并且你可以发送一些字节回去。一旦你发送了30个字节,客户端会打印出来(然后就会一直停在那里,因为我在这个协议中没有实现进一步的逻辑)。