导航

Python基础教程——14 网络编程

Posted on 2012-08-25 21:08  immiki  阅读(158)  评论(0编辑  收藏  举报

14-1 服务器

import socket
s = socket.socket()
host = socket.gethostname()
port = 10234
s.bind((host,port))
s.listen(5)
while True:
    c, addr = s.accept()
    print 'Got connection from', addr
    c.send('Thank you for connecting')
    c.close()
    

14-2 客户机

import socket
s = socket.socket()
host = socket.gethostname()
port = 10234


s.connect((host,port))
print s.recv(1024)
  运行示例


>>> from urllib import urlopen

>>> webpage = urlopen('http://www.python.org')
>>> import re
>>> text = webpage.read()
>>> m = re.search('<a href="([^"]+)" .*?>About</a>', text, re.IGNORECASE)
>>> m.group(1)
'/about/'
>>> m.group(0)
'<a href="/about/" title="About The Python Language">About</a>'
>>>