python Socket程式設計(一)

2021-09-01 04:08:09 字數 1851 閱讀 9499

python的tcp網路通訊也是基於套接字的程式設計,建立乙個服務端,服務端的作用就是接受客戶端的輸入,返回時間+客戶端內容:

''' created on 2012-3-8 @author: administrator ''' #!/usr/bin/env python from socket import * from time import ctime host='' port=21567 bufsiz=1024 addr=(host,port) tcpsersock = socket(af_inet,sock_stream) tcpsersock.bind(addr) tcpsersock.listen(5) while true: print 'waiting for connection...' tcpclisock,addr=tcpsersock.accept() print '...connection from',addr while true: data=tcpclisock.recv(bufsiz) if not data: break tcpclisock.send('[%s] %s' %(ctime(),data)) tcpclisock.close() tcpsersock.close()

客戶端就是向服務端發請求並讀出列印服務端返回的資料:

''' created on 2012-3-8 @author: administrator ''' #!/usr/bin/env python from socket import * from time import ctime host='localhost' port=21567 bufsiz=1024 addr=(host,port) tcpclisock = socket(af_inet,sock_stream) tcpclisock.connect(addr) while true: data=raw_input('>') if not data: break tcpclisock.send(data) data=tcpclisock.recv(bufsiz) if not data: break print data tcpclisock.close()

執行結果如下:

>yushh [fri mar 09 14:04:55 2012] yushh >woshi da bendan [fri mar 09 14:05:36 2012] woshi da bendan >

注意要點:

1、服務端socket(af_inet,sock_stream) 建立tcp連線套接字

2、tcpsersock.accept()

函式返回乙個socket和address的元組

乙個udp的服務端demo:

''' created on 2012-3-8 @author: administrator ''' #!/usr/bin/env python from socket import * from time import ctime host='' port=21567 bufsiz=1024 addr=(host,port) udpsersock = socket(af_inet,sock_dgram) udpsersock.bind(addr) while true: print 'waiting for connection...' data,addr = udpsersock.recvfrom(bufsiz) udpsersock.sendto('[%s] %s' %(ctime(),data),addr) print '...connection from and return to:',addr udpsersock.close()

注意要點:

1、sendto()和recvfrom()函式乙個是向指定位址發,乙個是獲得

2、由於是資料報,所以不能儲存客戶端的套接字,不管客戶端傳送什麼,服務端只能被動響應,也就是所有客戶端接收到的內容都是一樣的。

python Socket程式設計(一)

python的tcp網路通訊也是基於套接字的程式設計,建立乙個服務端,服務端的作用就是接受客戶端的輸入,返回時間 客戶端內容 created on 2012 3 8 author administrator usr bin env python from socket import from tim...

Python Socket 程式設計

client import socket,sys if name main 處理引數 argv sys.argv if len argv 3 or len argv 2 and argv 1 print useage argv 0 sys.exit 0 host argv 1 server ip位址...

python socket程式設計

python 編寫server的步驟 1.第一步是建立socket物件。呼叫socket建構函式。如 socket socket.socket family,type family引數代表位址家族,可為af inet或af unix。af inet家族包括internet位址,af unix家族用於...