Python的Socket模塊簡單使用
1、使用socket模塊編寫UDP服務端,代碼如下。從中需要注意的知識是:bind()和connect()函數都只有一個參數,參數是表示地址的元組(hostname,port),千萬不要寫成兩個參數了。
#! /usr/bin/env python #coding=utf-8 #使用socket模塊編寫的服務器(通過UDP傳輸數據) import socket s=socket.socket(socket.AF_INET,socket.SOCK_DGRAM) s.bind(("",10000)) #bind函數只有一個參數 while True: data,client=s.recvfrom(1024) print "receive a connection from %s" %str(client) #str()函數可以將元組轉換成字符串形式 #回顯 s.sendto("echo:"+data,client)
2、使用socket模塊編寫的UDP客戶端代碼:
#! /usr/bin/env python #coding=utf-8 #客戶端,基于UDP協議 import socket s=socket.socket(socket.AF_INET,socket.SOCK_DGRAM) s.sendto("hello",("localhost",10000)) data,addr=s.recvfrom(1024) print "receive data:%s from %s" %(data,str(addr))
3、使用socket模塊編寫的TCP服務端
#! /usr/bin/env python #coding=utf-8 import socket s=socket.socket(socket.AF_INET,socket.SOCK_STREAM,0) #也可以使用s=socket.socket()來通過默認參數來生成TCP的流套接字 #host='' host可以為空,表示bind()函數可以綁定在所有有效地地址上 host="localhost" port=1235 s.bind((host,port)) #注意,bind函數的參數只有一個,是(host,port)的元組 s.listen(3) while True: client,ipaddr=s.accept() print "Got a connect from %s" %str(ipaddr) data=client.recv(1024) print "receive data:%s" %data client.send("echo:"+data) client.close()
4、使用socket模塊編寫的TCP客戶端;
#! /usr/bin/env python #coding=utf-8 import socket s=socket.socket(socket.AF_INET,socket.SOCK_STREAM,0) #服務器的主機名和端口 host="localhost" port=1235 s.connect((host,port)) s.send("i am client") data=s.recv(1024) print "Reply from server-----%s" %data
本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!