Python中的網絡編程比C語言中要簡潔不少,畢竟封裝了大量的細節。python
因此這裏再也不介紹網絡編程的基本知識。並且我認爲,從Python學習網絡編程不是一個明智的選擇。編程
簡單的TCP鏈接ubuntu
服務器代碼以下:服務器
import socket from time import ctime sock = socket.socket() sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) sock.bind(('localhost', 9981)) sock.listen(5) while True: print 'waiting for connection ...' peersock, peeraddr = sock.accept() print '....connected from:', peeraddr while True: data = peersock.recv(1024) if not data: break peersock.send('[%s] %s' % (ctime(), data)) peersock.close() sock.close()
注意這裏設置了地址複用。網絡
這是一個時間戳服務器,同時server還將用戶的輸入直接回顯過去。socket
客戶端的代碼以下:學習
import socket sock = socket.socket() sock.connect(('localhost', 9981)) while True: data = raw_input('> ') if not data: break; sock.send(data) data = sock.recv(1024) if not data: break print data sock.close()
運行兩邊的代碼,這裏貼出客戶端的運行結果:spa
22:56:08 wing@ubuntu python python 2.py 1 ↵ > foo [Tue Nov 11 22:56:10 2014] foo > bar [Tue Nov 11 22:56:12 2014] bar >
簡單的UDP鏈接code
服務器代碼以下:server
from socket import * from time import ctime sock = socket(AF_INET, SOCK_DGRAM) sock.bind(('localhost', 9981)) while True: print 'waiting for message ...' data, addr = sock.recvfrom(1024) sock.sendto('[%s] %s' % (ctime(), data), addr) print '...received from and returned to:', addr sock.close()
客戶端代碼以下:
from socket import * addr = ('localhost', 9981) sock = socket(AF_INET, SOCK_DGRAM) while True: data = raw_input('> ') if not data: break; sock.sendto(data, addr) data, addr = sock.recvfrom(1024) if not data: break print data sock.close()
Python中還提供了其餘一系列的高級組件,例如TcpServer、ForkingTcpServer和ThreadingTCPServer等,後面會寫一篇文章,總結各類網絡編程的模型,到時候再去介紹。