Home > other >  Python3.8 HTTPServer port without stop
Python3.8 HTTPServer port without stop

Time:09-17

Below is my server code, running after a period of time is a different port 8090, but from in Windows to look at the port is occupied or not released, replaced several server has the problem,


. From the HTTP server import HTTPServer, BaseHTTPRequestHandler
The import json
The import configparser
The import socket

The class Resquest (BaseHTTPRequestHandler) :
Def handler (self) :
Print (" data: ", the self. Rfile. Readline (). The decode ())
Self. Wfile. Write (self) rfile) readline ())

Def do_GET (self) :
Print (self. Requestline)
If the self. The path!='/hello:
Self. Send_error (404, "Page not Found!" )
Return

Data={
https://bbs.csdn.net/topics/'result_code' : '1',
'result_desc' : 'Success',
'timestamp' : ' ',
"Data" : {' message_id ':' 25 d55ad283aa400af464c76d713c07ad}
}
Self. Send_response (200)
Self. Send_header (' the content-type ', 'application/json)
Self. End_headers ()
Self. Wfile. Write (json. Dumps (data) encode ())

Def do_POST (self) :
CIP=self. Client_address [0]
Print (' ClientIP='+ CIP)

Req_datas=self. Rfile. Read (int (self) headers [' content - length ']))
CH=req_datas. Decode ()

Self. Send_response (200)
Self. Send_header (' the content-type ', 'application/json)
Self. End_headers ()
Try:
Self. Wfile. Write (CH. Encode (' utf-8))
Except the Exception as e:
SErr=STR (e)
Print ('/' + CIP + ' '+' Error: '+ SErr)


If __name__=="__main__ ':
Httpserverport=8090
=(' host ', int (httpserverport))
Server=HTTPServer (host, Resquest)

Print (" Starting server, listen at: % s: % s "% host)
The hostname=socket. Gethostname ()
Print (' computer name: + hostname)
IP=socket. Gethostbyname (hostname)
Print (' computer IP: + IP)
Server. Serve_forever ()

CodePudding user response:

Kill process.

Started to read and save the pid, print or save to file,

 pid=OS. Getpid () # for process pid 

Under Windows using taskkill/pid 22222 (python reads the pid value)

CodePudding user response:

Not other process to take up this port, it is my own have been with the program, the program start port connection is normal, after running for a period of time even after the port is not top, Telnet and nothing

CodePudding user response:

Someone come across this kind of situation? I am using Python3.8

CodePudding user response:


1 the HTTPServer concurrency support is very poor, use ThreadingHTTPServer instead of HTTPServer

2 req_datas=self. Rfile. Read (int (self) headers [' content - length ']))
Without treatment length discrepancy, the block may be produced if the length is wrong,
3 class Resquest (BaseHTTPRequestHandler) : not a bad name, spelling errors, and should end with a Handler

CodePudding user response:

https://www.zybuluo.com/JunQiu/note/1350528

CodePudding user response:

"And why do you write their own httpserver is flask is not working or Django too complicated?
  • Related