標籤:
用戶端編程
#-*- coding:utf8 -*-import socket#建立一個socket#AF_INET指定使用IPv4協議,如果要用更先進的IPv6,就指定為AF_INET6。SOCK_STREAM指定使用面向流的TCP協議s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)#建立串連s.connect((‘www.sina.com.cn‘, 80))#發送資料(http請求)s.send(‘GET / HTTP/1.1\r\nHost: www.sina.com.cn\r\n\r\n‘)#接收資料buffer = []while True: #每次最多接受1k位元組 d = s.recv(1024) if d: buffer.append(d) else: breakdata = ‘‘.join(buffer)#關閉串連s.close()#分離http頭和主體header, html = data.split(‘\r\n\r\n‘, 1)print header#把接受到的資料寫入檔案with open(‘D:\\sina.html‘, ‘wb‘) as f: f.write(html)
伺服器編程
伺服器端
#-*- coding:utf8 -*-import socket, threading, timedef tcplink(sock, addr): print ‘Accept new connection from %s:%s...‘ %addr sock.send(‘Welcome‘) while True: data = sock.recv(1024) time.sleep(1) if data == ‘exit‘ or not data: break sock.send(‘Hello, %s‘ %data) sock.close() print ‘Connection from %s %s‘ %addr#建立sockets = socket.socket(socket.AF_INET, socket.SOCK_STREAM)#監聽連接埠s.bind((‘127.0.0.1‘, 9999))#傳入的參數指定等待串連的最大數量s.listen(5)print ‘Waiting for connection...‘while True: #接受一個新串連 sock, addr = s.accept() #建立新線程來處理TCP串連 t = threading.Thread(target=tcplink, args=(sock,addr)) t.start()
用戶端
#-*- coding:utf8 -*-import sockets = socket.socket(socket.AF_INET, socket.SOCK_STREAM)s.connect((‘127.0.0.1‘, 9999))print s.recv(1024)for data in [‘David‘, ‘Yt‘, ‘Amenda‘]: s.send(data) print s.recv(1024)s.send(‘exit‘)s.close()
2015-05-11
python之TCP編程