标签: httpserver

如何使用第一个可用端口在Python中创建HTTP服务器?

我想避免硬编码端口号,如下所示:

httpd = make_server('', 8000, simple_app)
Run Code Online (Sandbox Code Playgroud)

我以这种方式创建服务器的原因是我想将它用作Adobe AIR应用程序的"内核",因此它将使用PyAMF进行​​通信.由于我在客户端运行它,因此很有可能我定义的任何端口都已被使用.如果有更好的方法来做到这一点,我问错了问题,请告诉我.

python httpserver

3
推荐指数
2
解决办法
1604
查看次数

paste.httpserver并使用HTTP/1.1 Keep-alive减速; 用httperf和ab测试

我有一个基于paste.httpserver的Web服务器作为HTTP和WSGI之间的适配器.当我使用httperf进行性能测量时,如果每次使用--num-conn我开始一个新请求,我每秒可以执行超过1,000个请求.如果我改为使用--num-call重用连接,那么我每秒得到大约11个请求,速度的1/100.

如果我尝试ab,我会超时.

我的测试是

% ./httperf --server localhost --port 8080 --num-conn 100
...
Request rate: 1320.4 req/s (0.8 ms/req)
...
Run Code Online (Sandbox Code Playgroud)

% ./httperf --server localhost --port 8080 --num-call 100
...
Request rate: 11.2 req/s (89.4 ms/req)
...
Run Code Online (Sandbox Code Playgroud)

这是一个简单的可重现服务器

from paste import httpserver

def echo_app(environ, start_response):
    n = 10000
    start_response("200 Ok", [("Content-Type", "text/plain"),
                              ("Content-Length", str(n))])
    return ["*" * n]

httpserver.serve(echo_app, protocol_version="HTTP/1.1")
Run Code Online (Sandbox Code Playgroud)

它是一个多线程服务器,很难分析.这是一个单线程的变体:

from paste import httpserver

class MyHandler(httpserver.WSGIHandler):
    sys_version = None
    server_version = "MyServer/0.0"
    protocol_version = "HTTP/1.1"

    def log_request(self, *args, **kwargs):
        pass …
Run Code Online (Sandbox Code Playgroud)

python paste keep-alive httpserver httperf

3
推荐指数
1
解决办法
2775
查看次数

CBuilder中的HTTP服务器

我是CBuilder编程的新用户。我正在编写HTTP Server应用程序,它会同时接收混合数据:文本和二进制数据,但是我不知道wich组件以及如何使用它解析传入的请求。我的目的是将文本数据与二进制数据分开。谁能在Cbuilder或Delphi中显示示例。

delphi c++builder httpserver

3
推荐指数
1
解决办法
206
查看次数

我想与POCO HTTP服务器建立持久的TCP连接

我正在使用POCO C ++ lib版本1.4.3来实现HTTP服务器。在我的用例中,只有两个或三个客户端,我想拥有持久的连接。客户端发送带有放置请求的数据,服务器使用“ HTTP / 1.1 201 Created”(HTTP / 1.1 201已创建)进行应答。客户端打开多个连接。其中一个客户端可以同时打开20个连接。

我在HTTPServerParams和Poco :: Net :: ServerSocket(myPort)中使用默认值,并且在使用Poco :: ThreadPool(16,48)。

客户端发送一个http put请求,服务器将回答:

Server:
HTTP/1.1 201 Created
Connection: Close
Date: Thu, 31 Jan 2013 15:21:50 GMT
Run Code Online (Sandbox Code Playgroud)

我在带有WireShark的PCAP文件中看到了此结果。

如果我不希望服务器在放置请求后关闭连接,该怎么办?

---编辑并插入源代码:

HTTPServer::HTTPServer(uint16_t port, 
                       Poco::Net::HTTPRequestHandlerFactory* handlerFactory):
m_port(port),
m_wasStarted(false)
{
    // HTTPServer takes ownership
Poco::Net::HTTPServerParams*   options = new Poco::Net::HTTPServerParams; 

try
{
    m_threadPool.reset(new Poco::ThreadPool (16,48));

    std::cout << "HTTPServerParams.keepAlive: " 
                  << options->getKeepAlive() << std::endl;

    std::cout << "HTTPServerParams.keepAliveTimeout: " 
                  << options->getKeepAliveTimeout().totalSeconds() << std::endl;

    std::cout << "HTTPServerParams.MaxKeepAliveRequests: " 
                  << options->getMaxKeepAliveRequests()<< …
Run Code Online (Sandbox Code Playgroud)

c++ connection poco persistent httpserver

3
推荐指数
1
解决办法
3855
查看次数

无法从delphi中的TIdHTTP连接到TIdHTTPServer

我有一个应用程序使用TIdHTTPServer,并TIdHTTP在Delphi和我有这样的代码:

// This is for activating the HTTPServer - works as expected
HTTPServer1.Bindings.Add.IP := '127.0.0.1';
HTTPServer1.Bindings.Add.Port := 50001;
HTTPServer1.Active := True;
Run Code Online (Sandbox Code Playgroud)

这是OnCommandGet我的HTTPServer 的过程:

procedure TDataForm.HttpServer1CommandGet(AContext: TIdContext;
  ARequestInfo: TIdHTTPRequestInfo; AResponseInfo: TIdHTTPResponseInfo);
begin
  AResponseInfo.ContentText := 'Hello, user';
end;
Run Code Online (Sandbox Code Playgroud)

我只是不知道为什么这个程序不起作用:

procedure TDataForm.btnHTTPSendGetClick(Sender: TObject);
var
  HTTPClient : TIdHTTP;
  responseStream : TMemoryStream;
begin
  HTTPClient := TIdHTTP.Create;
  responseStream := TMemoryStream.Create;
  try
    try
      HTTPClient.Get('http://127.0.0.1:50001', responseStream);
    except on e : Exception do begin
      showmessage('Could not send get request to localhost, port 50001'); …
Run Code Online (Sandbox Code Playgroud)

delphi indy httpserver

3
推荐指数
1
解决办法
1750
查看次数

HttpExchange发送文件

我正在使用服务器分发一些文件(以zip格式),但是,我希望用户输入CAPTCHA,然后才能下载文件。

这带来了一个新问题,因为代码:

    private void sendFileResponse(final String filename, byte[] response, HttpExchange httpExchange) {
        //<editor-fold defaultstate="collapsed" desc="code">
        if (response != null && response.length > 0 && httpExchange != null) {
            try {
                httpExchange.setAttribute(HTTPExchange.HeaderFields.Content_Type.toString(), "application/zip");

                OutputStream outputStream = httpExchange.getResponseBody();
                httpExchange.sendResponseHeaders(200, response.length);
                outputStream.write(response);
                outputStream.flush();
                outputStream.close();
                httpExchange.getRequestBody().close();
            } catch (Exception e) {
                System.out.println(Misc.getStackTrace(e));
            }
        }
        //</editor-fold>
    }
Run Code Online (Sandbox Code Playgroud)

...将导致该文件被命名为下载请求网页的URL。例如,如果用户输入正确的验证码并从/download.html下载文件,则他们收到的文件将是download.html,而不是我的文件名。

如何使服务器将文件作为文件名发送并同时刷新网页?

谢谢。

java httpserver

3
推荐指数
1
解决办法
1791
查看次数

除了一个子域外,重定向所有子域名?

我有一个域example.com,并希望将所有子域重定向到http://example.com.但是一个例外是api.example.com的后端子域.

如何使用Nginx将其关闭?

nginx httpserver

3
推荐指数
1
解决办法
1469
查看次数

为什么do_GET比do_POST快得多

Python的BaseHTTPRequestHandler对于通过邮寄发送的表单存在问题!

我见过其他人问同样的问题(为什么GET方法比POST更快?),但我的情况时差太大(1秒)

Python服务器:

from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
import datetime


def get_ms_since_start(start=False):
    global start_ms
    cur_time = datetime.datetime.now()
    # I made sure to stay within hour boundaries while making requests
    ms = cur_time.minute*60000 + cur_time.second*1000 + int(cur_time.microsecond/1000)
    if start:
        start_ms = ms
        return 0
    else:
        return ms - start_ms

class MyServer(BaseHTTPRequestHandler, object):
    def do_GET(self):
        print "Start get method at %d ms" % get_ms_since_start(True)
        field_data = self.path
        self.send_response(200)
        self.end_headers()
        self.wfile.write(str(field_data))
        print "Sent response at %d ms" % get_ms_since_start()
        return

    def …
Run Code Online (Sandbox Code Playgroud)

post http basehttpserver httpserver basehttprequesthandler

3
推荐指数
1
解决办法
669
查看次数

返回响应后关闭HTTP服务器

我正在构建一个基于Go bot的小命令行,它与Instagram API交互.

Instagram API是基于OAuth的,因此对于基于命令行的应用程序来说并不是太好.

为了解决这个问题,我在浏览器中打开了相应的授权URL,并使用本地服务器启动了重定向URI - 这样我可以捕获并优雅地显示访问令牌,而不是需要从中获取此权限的用户URL手动.

到目前为止,应用程序可以成功打开浏览器到授权URL,您授权它并将它重定向到本地HTTP服务器.

现在,在向用户显示访问令牌之后我不需要HTTP服务器,因此我想在执行此操作后手动关闭服务器.

为此,我从这个答案中汲取灵感并鼓励以下内容:

package main

import (
    "fmt"
    "io"
    "log"
    "net/http"
    "os/exec"
    "runtime"
    "time"
)

var client_id = "my_client_id"
var client_secret = "my_client_secret"
var redirect_url = "http://localhost:8000/instagram/callback"

func main() {

    srv := startHttpServer()

    openbrowser(fmt.Sprintf("https://api.instagram.com/oauth/authorize/?client_id=%v&redirect_uri=%v&response_type=code", client_id, redirect_url))

    // Backup to gracefully shutdown the server
    time.Sleep(20 * time.Second)
    if err := srv.Shutdown(nil); err != nil {
        panic(err) // failure/timeout shutting down the server gracefully
    }
}

func showTokenToUser(w http.ResponseWriter, r *http.Request, srv …
Run Code Online (Sandbox Code Playgroud)

go httpserver

3
推荐指数
1
解决办法
642
查看次数

Python HTTP服务器保持连接活跃

我正在尝试测试用C编写的HTTP客户端,该客户端将HTTP POST请求发送到计算机上的本地服务器。我keep-alive在计算机上运行的python3 HTTP服务器上的POST请求中添加了标头,如下所示:

<ip-address-1> - - [29/Apr/2018 18:27:49] "POST /html HTTP/1.1" 200 -
Host: <ip-address-2>
Content-Type: application/json
Content-Length: 168
Connection: Keep-Alive
Keep-Alive: timeout=5, max=100


INFO:root:POST request,
Body:
{
"field": "abc",
"time": "2018-04-29T01:27:50.322000Z" 
}
Run Code Online (Sandbox Code Playgroud)

HTTP服务器POST处理程序如下所示:

class S(BaseHTTPRequestHandler):
    def _set_response(self):
        self.send_response(200)
        self.send_header('Content-type', 'text/html')
        self.send_header("Connection", "keep-alive")
        self.send_header("keep-alive", "timeout=5, max=30")
        self.end_headers()

    def do_POST(self):
        content_length = int(self.headers['Content-Length']) # <--- Gets the size of data
        post_data = self.rfile.read(content_length) # <--- Gets the data itself
        print(self.headers)
        logging.info("POST request,\nBody:\n%s\n", post_data.decode('utf-8'))

        self._set_response()
        self.wfile.write("POST request for {}".format(self.path).encode('utf-8'))

def …
Run Code Online (Sandbox Code Playgroud)

http httpserver http-headers python-3.x

3
推荐指数
1
解决办法
2273
查看次数