- android - RelativeLayout 背景可绘制重叠内容
- android - 如何链接 cpufeatures lib 以获取 native android 库?
- java - OnItemClickListener 不起作用,但 OnLongItemClickListener 在自定义 ListView 中起作用
- java - Android 文件转字符串
我想实现一个向 Python 发送请求的 TCP/IP 网络客户端应用程序 SocketServer并期望得到回应。我已经开始使用官方 Python SocketServer sample code :
server.py:
#!/usr/bin/env python
# encoding: utf-8
import SocketServer
class MyTCPHandler(SocketServer.StreamRequestHandler):
def handle(self):
request = self.rfile.readline().strip()
print "RX [%s]: %s" % (self.client_address[0], request)
response = self.processRequest(request)
print "TX [%s]: %s" % (self.client_address[0], response)
self.wfile.write(response)
def processRequest(self, message):
if message == 'request type 01':
return 'response type 01'
elif message == 'request type 02':
return 'response type 02'
if __name__ == "__main__":
server = SocketServer.TCPServer(('localhost', 12345), MyTCPHandler)
server.serve_forever()
client.py:
#!/usr/bin/env python
# encoding: utf-8
import socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
sock.connect(('127.0.0.1', 12345))
data = 'request type 01'
sent = sock.sendall(data + '\n')
if sent == 0:
raise RuntimeError("socket connection broken")
received = sock.recv(1024)
print "Sent: {}".format(data)
print "Received: {}".format(received)
data = 'request type 02'
sent = sock.sendall(data + '\n')
if sent == 0:
raise RuntimeError("socket connection broken")
received = sock.recv(1024)
print "Sent: {}".format(data)
print "Received: {}".format(received)
except Exception as e:
print e
finally:
sock.close()
server.py
输出:
RX [127.0.0.1]: request type 01
TX [127.0.0.1]: response type 01
client.py
输出:
Sent: request type 01
Received: response type 01
[Errno 54] Connection reset by peer
哪里做错了?似乎服务器正在关闭连接。我怎样才能让它保持打开状态?
注意:这是 C++/Qt: QTcpSocket won't write after reading 的后续问题
更新(在 abarnert's answer 之后):
我从中得到的是 SocketServer.StreamRequestHandler
不是最新的设计,虽然它允许我通过网络连接,但它并不真正支持我使用所有 TCP/我需要注意 IP 相关方面以实现稳健的通信。
这已在 Python 3 中通过 asyncio 得到解决。 ,但由于该项目存在于 Python 2 中,所以这不是一个选项。因此,我在 Twisted 中实现了上面描述的服务器和客户端。 :
server.py:
#!/usr/bin/env python
# encoding: utf-8
from twisted.internet.protocol import Factory
from twisted.protocols.basic import LineReceiver
from twisted.internet import reactor
class SimpleProtocol(LineReceiver):
def connectionMade(self):
print 'connectionMade'
# NOTE: lineReceived(...) doesn't seem to get called
def dataReceived(self, data):
print 'dataReceived'
print 'RX: %s' % data
if data == 'request type 01':
response = 'response type 01'
elif data == 'request type 02':
response = 'response type 02'
else:
response = 'unsupported request'
print 'TX: %s' % response
self.sendLine(response)
class SimpleProtocolFactory(Factory):
def buildProtocol(self, addr):
return SimpleProtocol()
reactor.listenTCP(12345, SimpleProtocolFactory(), interface='127.0.0.1')
reactor.run()
client.py:
#!/usr/bin/env python
# encoding: utf-8
from twisted.internet import reactor
from twisted.internet.protocol import Protocol
from twisted.internet.endpoints import TCP4ClientEndpoint, connectProtocol
class SimpleClientProtocol(Protocol):
def sendMessage(self, msg):
print "[TX]: %s" % msg
self.transport.write(msg)
def gotProtocol(p):
p.sendMessage('request type 01')
reactor.callLater(1, p.sendMessage, 'request type 02')
reactor.callLater(2, p.transport.loseConnection)
point = TCP4ClientEndpoint(reactor, '127.0.0.1', 12345)
d = connectProtocol(point, SimpleClientProtocol())
d.addCallback(gotProtocol)
reactor.run()
客户端不会关闭,而是空闲直到CTRL+C。 Twisted 可能需要一段时间才能让我理解,但对于手头的工作来说,使用经过测试和试用的框架显然比自己完成所有这些基础工作更合理。
最佳答案
这里的问题是,在 TCPHandler
中,“请求”实际上是一个完整的连接,从开始到结束。* 您的处理程序在 accept
时被调用,并且当您从它返回时,套接字将关闭。
如果你想在此基础上构建一个请求-响应-协议(protocol)处理程序,它在单个套接字级请求上处理多个协议(protocol)级请求,你必须自己做(或使用更高级别的框架) . (像 BaseHTTPServer
这样的子类演示了如何做到这一点。)
例如,您可以在handle
函数中使用一个循环。当然你可能想在这里添加一个异常处理程序和/或处理来自 rfile
的 EOF(注意 self.rfile.readline()
将返回 ''
用于 EOF,但 '\n'
用于空行,因此您必须在调用 strip
之前检查它,除非您希望空行表示“退出”在你的协议(protocol)中)。例如:
def handle(self):
try:
while True:
request = self.rfile.readline()
if not request:
break
request = request.rstrip()
print "RX [%s]: %s" % (self.client_address[0], request)
response = self.processRequest(request)
print "TX [%s]: %s" % (self.client_address[0], response)
self.wfile.write(response + '\n')
except Exception as e:
print "ER [%s]: %r" % (self.client_address[0], e)
print "DC [%s]: disconnected" % (self.client_address[0])
这将经常与您现有的客户端一起工作,至少在卸载机器上的本地主机上,但它实际上并不正确,而且“经常工作”很少足够好。参见 TCP sockets are byte streams, not message streams对于更长时间的讨论,但简而言之,您还需要做 David Schwarz's answer 中提到的事情:将换行符附加到您从服务器写入的内容(我已经在上面做了),并让客户端逐行读取,而不是一次只尝试读取 1024 个字节(您可以通过编写自己的缓冲区和-分割线代码,或仅通过使用 makefile
方法,因此它可以像服务器端一样使用 rfile.readline()
。)
不修复客户端不会导致回答 claim 的问题,但它会导致这样的问题:
Sent: request type 01
Received: resp
Sent: request type 02
Received: onse type 01
response typ
并且您可以看到,在实际尝试以编程方式处理响应的真实程序中,像 resp
或 onse type 01\nresponse typ
这样的响应不会发生非常有用……
* 请注意,SocketServer
是一种没有人真正喜爱的古老设计。 Python 3 添加 asyncio
是有原因的,Python 2 中的人们通常使用第三方框架,如 Twisted和 gevent .它们对于简单任务来说更简单,对于复杂任务来说更灵活/强大(并且效率更高)。
关于Python:SocketServer 意外关闭 TCP 连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29571770/
我正在使用的网站上有一个非 Canvas 导航。关闭 Canvas 导航的默认状态是关闭的,这在移动网站上运行良好,因为您可以打开它并选择您的链接,但在桌面上关闭它并打开它会隐藏用户的信息,我希望它是
我有一个 NSViewController 是这样连接的: 在底部 viewController 中,我尝试使用 self.dismiss(self) 关闭它,但是,它会产生此错误: [General
我昨天制作了一个扩展的 JQuery 搜索框,它的作用就像一个魅力!但是,我在创建一个脚本时遇到问题,当用户单击搜索框时,它会关闭。 这是我的 JQuery: function expandSearc
我一辈子都无法在 API V3 中一次只显示一个信息窗口。我需要一个在下一次开放之前关闭。还希望在 map 上的任何地方关闭 infoWindow onclick。这是否在初始化函数中? 这是我的完整
关闭和清理套接字的正确方法是什么? 我在辅助线程中运行 io_service,我需要关闭与主线程的连接: void closeConnection() { ioc.post([&socket]
我的 Selenium 测试看起来像这样:客户选择金融产品,填写一些必要的数据,并在打印预览中显示条款/协议(protocol)文档(根据本地法律的要求)。打印/关闭打印预览对话框后,客户输入更多数据
我目前正在从 android 网站了解 Navigation Drawer,我正在使用他们的示例 http://developer.android.com/training/implementing-
尝试通过 expo 在模拟器上运行 react-native 应用程序时出现此错误。 Couldn't start project on Android: Error running adb: adb
方法一 function transform(ar) { var alStr = []; for(var i=0; i
我想按以下方式自定义我的抽屉导航: 我希望在抽屉打开时显示一个图标,在抽屉关闭时显示另一个图标,而不是将菜单图标稍微向左滑动的当前默认动画。 关于我在哪里可以找到类似内容的任何想法/线索? 我做了一些
我们刚刚从 0.6.2 或 0.7 升级了我们的 dropwizard 版本,发现 .yml 文件中的很多配置都发生了变化。尽管我们能够弄清楚其中的大部分,但我们无法弄清楚如何关闭“requestLo
从 celery 2.4.5 升级后,我开始让 celery 随机关闭。 我在 centOS 机器上使用 celery 3.0.12、boto 2.6 和 amazon sqs 和 django 1.
我试图包含一些语句来指导用户更多地了解文件无法打开或关闭的原因。文件在写入模式下无法打开的一些可能情况是什么?无法关闭怎么办? FILE *fp; if(!(fp = fopen("testing",
我有一个DLL,可以访问数据库并从存储在配置文件中的应用程序设置中读取连接字符串。然后,引用此DLL的应用程序将需要在其配置文件中为此配置设置设置值。 我遇到的问题是,生成的配置代码会通过Defaul
我将 UIDatePicker 添加为 UITextField 的输入 View UIDatePicker *oBirth; NSDateFormatter *dateFormat; _edit
我有以下代码: SecondViewController *secondView = [[SecondViewController alloc] initWithNibName:@"SecondVie
Closed. This question does not meet Stack Overflow guidelines。它当前不接受答案。 想改善这个问题吗?更新问题,以便将其作为on-topic
通常,按下 option 键关闭窗口会关闭应用程序中的所有窗口。在我的应用程序中,我希望它仅关闭与用户正在关闭的窗口相关的窗口。我怎样才能做到这一点?我可以为所有窗口实现 windowShouldCl
我有一个 NSWindow,它托管一个已连接到脚本处理程序的 WebView。 现在,当用户单击 WebView 上的控件上的按钮时,它会调用我的对象上的 Objective C 方法。 在这种特定情
我想根据 MBP 上的相机使用情况自动化个人工作流程。 基本上我想知道是否任何 的摄像头(内置或 USB)已打开或关闭,因此我可以运行我将创建的程序或脚本。 我认为如果我需要轮询相机状态也可以,但基于
我是一名优秀的程序员,十分优秀!