python socket編程,pythonsocket
一、什麼是socket?
Python 官方關於 Socket 的函數請看 http://docs.python.org/library/socket.html
socket通常也稱作"通訊端",用於描述IP地址和連接埠,是一個通訊鏈的控制代碼,應用程式通常通過"通訊端"向網路發出請求或者應答網路請求。
socket起源於Unix,而Unix/Linux基本哲學之一就是“一切皆檔案”,對於檔案用開啟、讀寫、關閉模式來操作。socket就是該模式的一個實現,socket即是一種特殊的檔案,一些socket函數就是對其進行的操作(讀/寫IO、開啟、關閉)
file模組是針對某個指定檔案進行開啟、讀寫、關閉
socket模組是針對 伺服器端 和 用戶端Socket 進行開啟、讀寫、關閉
二、舉個執行個體
1 #!/usr/bin/env python 2 # _*_ coding: UTF-8 _*_ 3 # Author:taoke 4 import socket 5 import sys 6 try: 7 #建立socket 8 s = socket.socket(socket.AF_INET,socket.SOCK_STREAM) 9 except socket.error:10 #建立失敗,產生socket.error異常11 print("socket creat error:"+str(socket.error))12 sys.exit()13 14 print("creat socket")15 host = 'www.oschina.net'16 17 try:18 #擷取主機IP19 remote_ip = socket.gethostbyname(host)20 except socket.gaierror:21 print("hostname could not be resolved,exiting")22 sys.exit()23 print("IP address of "+host+" is "+remote_ip)24 port = 8025 #串連26 s.connect((remote_ip,port))27 print('Socket Connected to ' + host + ' on ip ' + remote_ip)28 #Send some data to remote server29 message = "GET / HTTP/1.1\r\nHost: oschina.net\r\n\r\n"30 31 try :32 #Set the whole string33 s.sendall(message.encode())34 except socket.error:35 #Send failed36 print('Send failed')37 sys.exit()38 39 print('Message send successfully')40 41 #Now receive data42 reply = s.recv(4096)43 44 print(reply.decode())45 #關閉socket46 s.close()
運行結果如下:
creat socketIP address of www.oschina.net is 139.199.91.153Socket Connected to www.oschina.net on ip 139.199.91.153Message send successfullyHTTP/1.1 301 Moved PermanentlyX-Proxy: dayu-proxyDate: Wed, 20 Sep 2017 13:28:07 GMTContent-Type: text/htmlContent-Length: 278X-DAYU-UUID: D7PRC9C6CFCF6932495F893F61E66ABDB60CConnection: keep-aliveSet-Cookie: __DAYU_PP=733na7yMm7VYJ7VbeQz3ffffffffef192cb9ef6a; Expires=Wed, 09 Jun 2021 23:59:59 GMT; Path=/Location: http://www.oschina.net/<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN"><html><head><title>301 Moved Permanently</title></head><body bgcolor="white"><h1>301 Moved Permanently</h1><p>The requested resource has been assigned a new permanent URI.</p><hr/>Powered by Tengine</body></html>
TCP用戶端:
1 建立通訊端,串連遠端地址
# socket.socket(socket.AF_INET,socket.SOCK_STREAM) , s.connect()
2 串連後發送資料和接收資料
# s.sendall(), s.recv()
3 傳輸完畢後,關閉通訊端
#s.close()