CWYAlpha

Just another WordPress.com site

Thought this was cool: Python写简单的网络服务器示例

leave a comment »


“Life is short, you need Python!”


用Python写一个socket服务有多难?

import socket
server = socket.socket()
server.bind(("", 8000))
server.listen(1)
while True:
    fd, addr = server.accept()
    fd.send(str(addr))

测试:

root@xiaoxia-pc:~# telnet xiaoxia 8000
Trying 127.0.0.1…
Connected to xiaoxia.
Escape character is ‘^]’.
(‘127.0.0.1’, 38603)^]
telnet> Connection closed.

用Python写一个HTTP回应服务有多难?

from BaseHTTPServer import *
class MyHTTPHandler(BaseHTTPRequestHandler):
    def do_GET(self):
        self.wfile.write("Hello world.")
server = HTTPServer(("", 8000), MyHTTPHandler)
server.serve_forever()

测试:

用Python写一个HTTP资源请求服务有多难?

import SimpleHTTPServer
import BaseHTTPServer
server = BaseHTTPServer.HTTPServer(("", 8000), SimpleHTTPServer.SimpleHTTPRequestHandler)
server.serve_forever()

测试:

这些代码很简短,就实现了很多功能,而且扩展性也很强,

例如这个,《写了一个Web Gateway做Proxy》

这个,《Python小程序: ServerInformation》

这个,《用Python写socks5服务器端》

还有这个,《用Python写一个本地Sogou代理服务器程序》

from Xiaoxia[PG]: http://xiaoxia.org/2011/11/03/python-server-examples/

Written by cwyalpha

十一月 24, 2012 在 3:43 下午

发表在 Uncategorized

发表评论

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / 更改 )

Twitter picture

You are commenting using your Twitter account. Log Out / 更改 )

Facebook photo

You are commenting using your Facebook account. Log Out / 更改 )

Google+ photo

You are commenting using your Google+ account. Log Out / 更改 )

Connecting to %s

%d 博主赞过: