背景:项目需要测试负载均衡,手动搭建一个http服务器
参考链接:https://blog.csdn.net/ordeder/article/details/22490373
遇到的问题:
1、NameError: name 'file' is not defined
解决方法:我用的是python3.6.4,根据上述链接代码操作,打开文件的方式file()改成open()

2、OSError: [WinError 10048] 通常每个套接字地址(协议/网络地址/端口)只允许使用一次

解决方法:打开任务管理器,杀掉“python.exe”的进程,重新编译,在浏览器输入“http://192.168.85.100:49592/”,就可以看到请求了


3、TypeError: a bytes-like object is required, not 'str'
把string类型的返回值改成bytes类型

4、TypeError: string argument without an encoding
解决方法:把bytes(responsebytes)改成(response,encoding = "utf8")

调试成功后的python代码,欢迎使用
#!/usr/bin/python
import socket
import signal
import errno
from time import sleep
def HttpResponse(header,whtml):
f =open(whtml)
contxtlist = f.readlines()
context = ''.join(contxtlist)
response = "%s %d\n\n%s\n\n" % (header,len(context),context)
return bytes(response,encoding = "utf8")
def sigIntHander(signo,frame):
print ('get signo# ',signo)
global runflag
runflag = False
global lisfd
lisfd.shutdown(socket.SHUT_RD)
#输入本地IP
strHost = "192.168.85.100"
#socket.inet_pton(socket.AF_INET,strHost)
HOST = strHost
#输入端口号
PORT = 49592
httpheader = '''\
HTTP/1.1 200 OK
Context-Type: text/html
Server: Python-slp version 1.0
Context-Length: '''
lisfd = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
lisfd.bind((HOST, PORT))
lisfd.listen(2)
signal.signal(signal.SIGINT,sigIntHander)
runflag = True
while runflag:
try:
confd,addr = lisfd.accept()
except socket.error as e:
if e.errno == errno.EINTR:
print ('get a except EINTR')
else:
raise
continue
if runflag == False:
break;
print ("connect by ",addr)
data = confd.recv(1024)
if not data:
break
print (data)
confd.send(HttpResponse(httpheader,'index.html'))
# confd.send({"code":"404"})
confd.close()
else:
print ('runflag#',runflag)
print ('Done')
index.html内容:
<html>
<head>
<title>Python Server</title>
</head>
<body>
<h1>Hello python</h1>
<p>Welcom to the python world</br>
</body>
</html>
网友评论