Socket是應(yīng)用層與TCP/IP協(xié)議簇通信的中間層,可以看作提供給應(yīng)用層所用的接口。 Python中,主要用socket.socket([family[, type[, proto]]])方法來創(chuàng)建一個socket實(shí)例,相關(guān)參數(shù)說明: family - 套接字地址結(jié)構(gòu),有AF_INET、AF_INET6和AF_UNIX。 type - 數(shù)據(jù)傳輸?shù)念愋?,廣泛使用的有SOCK_STREAM(數(shù)據(jù)流)和SOCK_DGRAM(數(shù)據(jù)報文),SOCK_STREAM是面向連接的,SOCK_DGRAM是無連接的,如ATM和TCP協(xié)議屬于SOCK_STREAM類型,而IRDA和UDP協(xié)議屬于SOCK_DGRAM類型。 proto - 指明所要接收的協(xié)議包。 UDP小實(shí)例 server.py01 import socket 02 03 server = socket.socket(socket.AF_INET,socket.SOCK_DGRAM) 04 server.bind(("127.0.0.1",17800)) 05 print("udp server start") 06 while True: 07 data,addr = server.recvfrom(1024) 08 text = str(data, encoding = "utf-8") 09 print("address:%s data:%s"%(addr,text)) 10 if text == "quit": 11 break 12 print("udp server finish") 13 server.close() client.py01 import socket 02 03 client = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) 04 print("udp client start") 05 while True: 06 data = input("please input content:") 07 client.sendto(bytes(data,"utf-8"),("127.0.0.1", 17800)) 08 if data == "quit": 09 break 10 print("udp client finish") 11 client.close() 先運(yùn)行server.py,再運(yùn)行client.py,運(yùn)行結(jié)果: TCP小例子 server.py代碼01 import socket 02 03 server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 04 server.bind(("127.0.0.1",17800)) 05 server.listen(5) 06 print("tcp server start") 07 while True: 08 conn,addr = server.accept() 09 print("client connect, address: ",addr) 10 conn.send(b"welcome to server") 11 data = conn.recv(1024) 12 print(str(data,encoding="utf-8")) 13 conn.close() 14 print("tcp server finish") 15 server.close() client.py代碼01 import socket 02 03 print("udp client1 start") 04 client1 = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 05 client1.connect(("127.0.0.1",17800)) 06 data1 = client1.recv(1024) 07 print(str(data1,encoding="utf-8")) 08 client1.send(b'I am client1') 09 client1.close() 10 print("udp client1 finish") 11 12 print("udp client2 start") 13 client2 = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 14 client2.connect(("127.0.0.1",17800)) 15 data2 = client2.recv(1024) 16 print(str(data2,encoding="utf-8")) 17 client2.send(b'I am client2') 18 client2.close() 19 print("udp client2 finish") 先運(yùn)行server.py,再運(yùn)行client.py,運(yùn)行結(jié)果: 本人一直都是做B/S方面的,對socket通信方面的認(rèn)識還很膚淺,只停留在如何應(yīng)用的層次,以后還需要多多研究和努力。這里有幾個心得: - 使用UDP數(shù)據(jù)報文套接方式,系統(tǒng)會自動分配端口號,客戶機(jī)不需要調(diào)用bind()函數(shù)顯示指定,而是用UNIX域數(shù)據(jù)報套接字就必須調(diào)用bind()函數(shù)來顯示指定路徑名 - Python文檔中已經(jīng)有若干個socket通信的例子,包括IPV4、IPV6下的TCP通信,大家可以去看看。在Doc文件夾下面的chm幫助文檔真是好東西,E文好的朋友,可以多去看看。 |
|