Python

来自软件开发
跳转至: 导航搜索

Socket服务端

import socket
import sys

serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = socket.gethostname()
port = 9999
serversocket.bind((host, port))
serversocket.listen(5)

while True:
    # 建立客户端连接
    clientsocket,addr = serversocket.accept()

    print("连接地址: %s" % str(addr))
    
    msg = '欢迎访问菜鸟教程!' + "\r\n"
    clientsocket.send(msg.encode('utf-8'))
    clientsocket.close()

Socket客户端

import socket
import sys
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 
host = socket.gethostname() 
port = 9999
s.connect((host, port))
msg = s.recv(1024)
s.close()
print(msg.decode('utf-8'))

Python内置HTTP服务(SimpleHTTPServer)

1、python开启http服务器

python -m SimpleHTTPServer 9999(自定义端口)

如果提示错误:

python.exe: No module named SimpleHTTPServer

则试一下命令:

python -m http.server

2、执行py脚本文件,开启cgi映射

python -m http.server --cgi 8000

py代码里添加

header = 'Content-Type: text/html\n'
print(header)

比如/cgi-bin/1.py文件代码:

header = 'Content-Type: text/html\n'
html = 'abc'
print(header)
print(html)

访问http://127.0.0.1:8000/cgi-bin/1.py

可以正常输出abc


Ps:

py代码文件默认目录在cgi-bin或者htbin

http.server官方文档 https://docs.python.org/3/library/http.server.html

参考资料