简体   繁体   English

如何知道服务器是否在python请求模块中关闭连接

[英]How to get to know if server closing the connection in python requests module

I am using python requests module in order to generate the traffic to my web server, 我正在使用python请求模块来生成到我的Web服务器的流量,

After certain request connection suppose to break and I want to run some callback if connection got closed( maybe server is sending the FIN or RESET flag). 在某些请求连接之后假设中断并且我想在连接关闭时运行一些回调(可能服务器正在发送FIN或RESET标志)。

How can I find if server or closing the connection in Requests module, I don't want to use tcpdump or any packet capturing utility to verify that. 如何在Requests模块中找到服务器或关闭连接,我不想使用tcpdump或任何数据包捕获实用程序来验证。

 82     def request_per_session(self, request, method='post', page=None,**options):
 83         url=self.url
 84         if page:url+=page
 85         print pprint.pprint(options)
 86         s = requests.Session()
 87         httpmethodToCall = getattr(s, method)
 88         print pprint.pprint(httpmethodToCall)
 89         for n in range(request):
 90             print "running %d" %n
 91             if method == 'get':
 92                 r=httpmethodToCall(url)
 93             else:
 94                 r=httpmethodToCall(url,options)
 95             print r.status_code

This can be more effectively accomplished with a port scanner. 使用端口扫描仪可以更有效地完成此操作。

To elaborate, I'm assuming you are sending/receiving data on port 80. With this information, merely create a socket, try to connect to the given host, and if there is an error you can either pass back the exception or print it out. 详细说明,我假设您正在端口80上发送/接收数据。有了这些信息,只需创建一个套接字,尝试连接到给定的主机,如果有错误,您可以传回异常或打印它出。 For example: 例如:

import socket

def checkServer(server):
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    try:
        socket.connect((socket.gethostbyname(server), 80))
        return None
    except socket.error as e:
        return e

In this code, if there is no error, then nothing is passed back(in the form of None ), but if there is an error, the exception object is passed back. 在此代码中,如果没有错误,则不传回任何内容(以None的形式),但如果有错误,则传回异常对象。 The code is a lot cleaner than using the Requests module because it deals with low-level connections, which are great if you want to check if things are open, passing data, and so on, but are terrible for sending data, scraping webpages, and so on. 代码比使用Requests模块更清晰,因为它处理低级别连接,如果你想检查事物是否打开,传递数据等等,这很好,但是发送数据,抓取网页,等等。 Something like urllib2 or requests would be better suited for that. urllib2或者requests类的东西会更适合。

I hope this helps. 我希望这有帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM