纯python套接字模块 [英] pure python socket module
问题描述
Python中的套接字模块包装了C实现的 _socket
模块。同样,socket.socket将使用 _sock
参数,该参数必须实现 _socket
接口。在某些方面, _sock
必须是 _socket
中底层套接字类型的实际实例,因为C代码确实进行了类型检查(不同于纯python)。
The socket module in python wraps the _socket
module which is the C implementation stuff. As well, socket.socket will take a _sock
parameter that must implement the _socket
interface. In some regards _sock
must be an actual instance of the underlying socket type from _socket
since the C code does type checking (unlike pure python).
鉴于您可以为 _sock
传递类似套接字的对象您可以编写一个套接字仿真器,然后将其传递给socket.socket。它需要模拟底层的套接字行为,但是要在内存中而不是通过真实的网络或其他任何东西。否则,它不应与 _socket
区分开。
Given that you can pass in a socket-like object for _sock
, it seems like you could write a socket emulator that you could pass in to socket.socket. It would need to emulate the underlying socket behavior but in memory and not over a real network or anything. It should not otherwise be distinguishable from _socket
.
要构建这种仿真需要什么?
I知道,我知道,这不是很实际。实际上,我学到了很难的方法,即使用常规套接字更容易,并且不需要使用虚假套接字。我以为我可以使用假套接字更好地控制测试环境。不管我何时被浪费,我发现我在此过程中都学到了一些有关套接字和python的知识。
I know, I know, this is not terribly practical. In fact, I learned the hard way that using regular sockets was easier and fake sockets were unnecessary. I had thought that I would have better control of a test environment with fake sockets. Regardless of the time I "wasted", I found that I learned a bunch about sockets and about python in the process.
我猜想任何解决方案都必须是像这样的交互对象堆栈:
I was guessing any solution would have to be a stack of interacting objects like this:
something_that_uses_sockets (like XMLRPCTransport for ServerProxy)
|
V
socket.socket
|
V
FakeSocket
|
V
FakeNetwork
|
V
FakeSocket ("remote")
|
V
socket.socket
|
V
something_else_that_uses_sockets (like SimpleXMLRPCServer)
对于真实的套接字,除了真实的网络而不是假的网络(加上操作系统级别的套接字),还有 _socket
而不是FakeSocket。
It seems like this is basically what is going on for real sockets, except for a real network instead of a fake one (plus OS-level sockets), and _socket
instead of FakeSocket.
无论如何,只是出于娱乐目的,关于如何解决这个问题的任何想法?
附带地,使用FakeSocket您可以在Google Apps中做一些类似套接字的工作...
Incidently, with a FakeSocket you could do some socket-like stuff in Google Apps...
推荐答案
已经完成了。 Twisted 广泛使用此协议对其协议实现进行单元测试。一个很好的起点应该是查看
It's already been done. Twisted uses this extensively for unit tests of its protocol implementations. A good starting place would be looking at some of Twisted's unit tests.
本质上,您只需调用 makeConnection ,且传输方式未连接到真正的套接字。超级容易!
In essence, you'd just call makeConnection on your protocol with a transport that isn't connected to a real socket. Super easy!
这篇关于纯python套接字模块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!