python socket程式設計

2021-07-11 18:44:43 字數 2194 閱讀 3731

客戶端**:

#__author__ = 'lenovo'

fromsocketimport*host='localhost'port=2157

bufsize=1024

addr=(host, port)

tcpclient=socket(af_inet, sock_stream)

tcpclient.connect(addr)

while true:data=input

('>')

if notdata:breaktcpclient.send(data.encode(encoding='utf_8'))

#需要將string型別的字串轉化為二進位制,需要進行二進位制編碼操作

data=tcpclient.recv(bufsize)

if notdata:breakprint

(data)

tcpclient.close()

伺服器端**:

#__author__ = 'lenovo'

fromsocketimport*fromtimeimportctime

host='localhost'port=2157

bufsize=1024

addr=(host, port)

serversocket=socket(af_inet, sock_stream)

serversocket.bind(addr)

serversocket.listen(5)

while true:print

('wating for connection....')

tcpclient,addr=serversocket.accept()

#accept函式返回乙個pair,其中第乙個返回值為sokcet鏈結,第二個返回值微客戶端的address

print

('.....connect from')

while true:data=tcpclient.recv(bufsize)

if notdata:print

('not data')

tcpclient.send((

'[%s] %s'%(ctime()

, data)).encode(encoding='utf_8'))

tcpclient.close()

serversocket.close()

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家族用於...

Python Socket程式設計

在使用python做socket程式設計時,因為須要使用堵塞 預設 的方式來讀取資料流。此時對於資料的結束每次都須要自己處理。太麻煩。而且網上也沒找到太好的封裝。所以就自己寫了個簡單的封裝。封裝思路 1.客戶端每次請求均傳送乙個 socketrequest 物件,當中封裝詳細的資料。這裡使用json...