我使用以下关键代码构建了一个服务器以使用 Windows 命名管道:
def run( self ):
# This is the main server loop for the Win32 platform
import win32pipe
import win32file
self.pipeHandle = win32pipe.CreateNamedPipe(
'\\\\.\\pipe\\myapp_requests',
win32pipe.PIPE_ACCESS_DUPLEX,
win32pipe.PIPE_TYPE_BYTE |
win32pipe.PIPE_READMODE_BYTE |
win32pipe.PIPE_WAIT,
1,
4096,
4096,
10000,
None)
if self.pipeHandle == win32file.INVALID_HANDLE_VALUE:
print 'Failed to create named pipe %s!' % self.pipeName
print 'Exiting...'
sys.exit(1)
while True:
# Open file connection
win32pipe.ConnectNamedPipe( self.pipeHandle )
# Run the main message loop until it exits, usually because
# of a loss of communication on the pipe
try:
self.messageLoop()
except ServerKillSignal:
break
# Return the pipes to their disconnected condition and try again
try: win32pipe.DisconnectNamedPipe( self.pipeHandle )
except: pass
win32file.CloseHandle( self.pipeHandle )
print "Exiting server"
该方法messageLoop()
使用 , 从管道读取数据win32file.ReadFile()
,直到抛出 win32file.error。然后它退出,允许 run() 重新启动它。
在我的实现中,用户不太可能具有管理员访问权限,因此无法将其作为系统服务启动。相反,我对客户端进行了编码,以检查 '\.\pipe\pyccf_requests' 处的管道是否存在。如果它不存在,则客户端启动一个新的服务器进程。