python server.py_用Python编写一个简单的Http Server

本文介绍了如何使用Python的BaseHTTPServer模块创建一个简单的HTTP服务器,展示如何返回'Hello World',提供静态文件如HTML、CSS等,并演示如何从HTML表单读取数据。
摘要由CSDN通过智能技术生成

用Python编写一个简单的Http Server

Python内置了支持HTTP协议的模块,我们可以用来开发单机版功能较少的Web服务器。Python支持该功能的实现模块是BaseFTTPServer, 我们只需要在项目中引入就可以了:

from BaseHTTPServer import BaseHTTPRequestHandler,HTTPServer

1

Hello world !

Let’s start with the first basic example. It just return “Hello World !” on the web browser.

让我们来看第一个基本例子,在浏览器上输出”Hello World ”

example1.py

#!/usr/bin/python

from BaseHTTPServer import BaseHTTPRequestHandler,HTTPServer

PORT_NUMBER = 8080

#This class will handles any incoming request from

#the browser

class myHandler(BaseHTTPRequestHandler):

#Handler for the GET requests

def do_GET(self):

self.send_response(200)

self.send_header('Content-type','text/html')

self.end_headers()

# Send the html message

self.wfile.write("Hello World !")

return

try:

#Create a web server and define the handler to manage the

#incoming request

server = HTTPServer(('', PORT_NUMBER), myHandler)

print 'Started httpserver on port ' , PORT_NUMBER

#Wait forever for incoming htto requests

server.serve_forever()

except KeyboardInterrupt:

print '^C received, shutting down the web server'

server.socket.close()

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

执行以下命令运行:

python example1.py

用你的浏览器打开这个地址http://your_ip:8080

浏览器上将会显示”Hello World !” 同时在终端上将会出现两条日志信息:

Started httpserver on port 8080

10.55.98.7 - - [30/Jan/2012 15:40:52] “GET / HTTP/1.1” 200 -

10.55.98.7 - - [30/Jan/2012 15:40:52] “GET /favicon.ico HTTP/1.1” 200 -

Serve static files

让我们来尝试下提供静态文件的例子,像index.html, style.css, javascript和images:

example2.py

#!/usr/bin/python

from BaseHTTPServer import BaseHTTPRequestHandler,HTTPServer

from os import curdir, sep

PORT_NUMBER = 8080

#This class will handles any incoming request from

#the browser

class myHandler(BaseHTTPRequestHandler):

#Handler for the GET requests

def do_GET(self):

if self.path=="/":

self.path="/index_example2.html"

try:

#Check the file extension required and

#set the right mime type

sendReply = False

if self.path.endswith(".html"):

mimetype='text/html'

sendReply = True

if self.path.endswith(".jpg"):

mimetype='image/jpg'

sendReply = True

if self.path.endswith(".gif"):

mimetype='image/gif'

sendReply = True

if self.path.endswith(".js"):

mimetype='application/javascript'

sendReply = True

if self.path.endswith(".css"):

mimetype='text/css'

sendReply = True

if sendReply == True:

#Open the static file requested and send it

f = open(curdir + sep + self.path)

self.send_response(200)

self.send_header('Content-type',mimetype)

self.end_headers()

self.wfile.write(f.read())

f.close()

return

except IOError:

self.send_error(404,'File Not Found: %s' % self.path)

try:

#Create a web server and define the handler to manage the

#incoming request

server = HTTPServer(('', PORT_NUMBER), myHandler)

print 'Started httpserver on port ' , PORT_NUMBER

#Wait forever for incoming htto requests

server.serve_forever()

except KeyboardInterrupt:

print '^C received, shutting down the web server'

server.socket.close()

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

这个新样例实现功能:

检查请求文件扩展名

设置正确的媒体类型返回给浏览器

打开请求的文件

发送给浏览器

输入如下命令运行它:

python example2.py

然后用你的浏览器打开 http://your_ip:8080

一个首页会出现在你的浏览器上

Read data from a form

现在探索下如何从html表格中读取数据

example3.py

#!/usr/bin/python

from BaseHTTPServer import BaseHTTPRequestHandler,HTTPServer

from os import curdir, sep

import cgi

PORT_NUMBER = 8080

#This class will handles any incoming request from

#the browser

class myHandler(BaseHTTPRequestHandler):

#Handler for the GET requests

def do_GET(self):

if self.path=="/":

self.path="/index_example3.html"

try:

#Check the file extension required and

#set the right mime type

sendReply = False

if self.path.endswith(".html"):

mimetype='text/html'

sendReply = True

if self.path.endswith(".jpg"):

mimetype='image/jpg'

sendReply = True

if self.path.endswith(".gif"):

mimetype='image/gif'

sendReply = True

if self.path.endswith(".js"):

mimetype='application/javascript'

sendReply = True

if self.path.endswith(".css"):

mimetype='text/css'

sendReply = True

if sendReply == True:

#Open the static file requested and send it

f = open(curdir + sep + self.path)

self.send_response(200)

self.send_header('Content-type',mimetype)

self.end_headers()

self.wfile.write(f.read())

f.close()

return

except IOError:

self.send_error(404,'File Not Found: %s' % self.path)

#Handler for the POST requests

def do_POST(self):

if self.path=="/send":

form = cgi.FieldStorage(

fp=self.rfile,

headers=self.headers,

environ={'REQUEST_METHOD':'POST',

'CONTENT_TYPE':self.headers['Content-Type'],

})

print "Your name is: %s" % form["your_name"].value

self.send_response(200)

self.end_headers()

self.wfile.write("Thanks %s !" % form["your_name"].value)

return

try:

#Create a web server and define the handler to manage the

#incoming request

server = HTTPServer(('', PORT_NUMBER), myHandler)

print 'Started httpserver on port ' , PORT_NUMBER

#Wait forever for incoming htto requests

server.serve_forever()

except KeyboardInterrupt:

print '^C received, shutting down the web server'

server.socket.close()

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

运行这个例子:

python example3.py

在 “Your name” 标签旁边输入你的名字

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 使用 Python 实现跨局域网聊天需要使用 socket 模块,具体实现步骤如下: 1. 建立 socket 连接,使用 socket.AF_INET 和 socket.SOCK_STREAM 指定 IPV4 协议和 TCP 协议。 2. 绑定 IP 地址和端口号。 3. 设置监听,使用 listen() 函数。 4. 等待客户端连接,使用 accept() 函数。 5. 接收和发送数据,使用 recv() 和 send() 函数。 6. 关闭连接,使用 close() 函数。 如果要实现 UI 界面,可以使用 Tkinter 模块进行构建。具体实现过程可能比较复杂,建议先了解相关知识,再尝试编写. ### 回答2: 要实现一个跨局域网的聊天程序,可以使用Python和相关的第三方库来完成。为了添加UI界面,可以使用PyQt或Tkinter等库。 首先,需要选择一个网络通信协议,例如TCP或者UDP。假设我们选择使用TCP。然后,按照以下步骤进行开发: 1. 导入所需的库: ``` import socket from tkinter import * ``` 2. 创建GUI窗口: ``` root = Tk() root.title("网络聊天") root.geometry("400x400") ``` 3. 创建输入框和发送按钮: ``` msg_box = Entry(root, width=50) msg_box.pack() def send_msg(): msg = msg_box.get() # 在这里添加将消息发送给远程主机的代码 msg_box.delete(0, END) send_button = Button(root, text="发送", command=send_msg) send_button.pack() ``` 4. 创建用于显示聊天内容的文本框: ``` chat_box = Text(root, width=50, height=25) chat_box.pack() ``` 5. 创建网络连接: ``` def connect(): global sock sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # 在这里添加远程主机的IP地址和端口号 server_address = ('remote_host_ip', remote_host_port) sock.connect(server_address) connect_button = Button(root, text="连接", command=connect) connect_button.pack() ``` 6. 创建接收和显示远程主机发送的消息的函数: ``` def receive_msg(): while True: msg = sock.recv(1024).decode('utf-8') chat_box.insert(END, msg) # 启动一个新线程来接收消息 import threading receive_thread = threading.Thread(target=receive_msg) receive_thread.start() ``` 7. 运行GUI窗口: ``` root.mainloop() ``` 在上述代码中,我们使用socket库来进行网络通信,Tkinter库创建UI界面。首先,用户需要填写远程主机的IP地址和端口号,然后点击连接按钮。接下来,用户可以在输入框中输入消息并点击发送按钮来发送消息。从远程主机接收到的消息将会显示在聊天框中。 注意:这只是一个简单的例子,可能需要添加更多的错误处理和异常处理来提高程序的稳定性和健壮性。 ### 回答3: 使用python编写一个跨局域网的聊天程序,需要使用到Python的socket模块来实现网络通信功能,并结合第三方库如Tkinter来创建UI界面。 以下是一个简单的示例代码: ```python import socket import threading from tkinter import Tk, Scrollbar, Label, END, Entry, Text, VERTICAL, Button, messagebox class ChatUI: def __init__(self, host, port): self.client = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.client.connect((host, port)) self.window = Tk() self.window.title("跨局域网聊天") scrollbar = Scrollbar(self.window) scrollbar.pack(side=RIGHT, fill=Y) self.text_area = Text(self.window, height=20, width=50) self.text_area.pack() self.text_area.config(yscrollcommand=scrollbar.set) scrollbar.config(command=self.text_area.yview) self.label = Label(self.window, text="输入消息:") self.label.pack() self.entry = Entry(self.window, width=50) self.entry.pack() self.send_button = Button(self.window, text="发送", command=self.send_message) self.send_button.pack() self.receive_thread = threading.Thread(target=self.receive_message) self.receive_thread.start() self.window.protocol("WM_DELETE_WINDOW", self.on_closing) def send_message(self): message = self.entry.get() self.entry.delete(0, END) self.client.send(message.encode('utf-8')) def receive_message(self): while True: try: message = self.client.recv(1024).decode('utf-8') self.text_area.insert(END, message + "\n") self.text_area.see(END) except: print("发生错误。") self.client.close() break def on_closing(self): if messagebox.askokcancel("退出", "确定要退出吗?"): self.client.close() self.window.destroy() if __name__ == '__main__': host = '服务器IP地址' port = 12345 ChatUI(host, port) ``` 要使该程序跨局域网正常运行,需要设置正确的服务器IP地址,可以将代码中的`host`变量替换为服务器的IP地址。同时,也需要确保服务器端正确监听该IP地址和端口号。 在运行程序之后,会弹出一个包含发送消息和显示接收消息的UI界面。在输入框中输入消息并点击发送按钮,消息将被发送到服务器并显示在文本区域中。同时,程序也会持续接收来自服务器的消息并显示在文本区域中。用户可以通过关闭窗口来退出程序。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值