您好,登錄后才能下訂單哦!
本篇文章為大家展示了怎么在Python中利用socket發(fā)送信息,內(nèi)容簡(jiǎn)明扼要并且容易理解,絕對(duì)能使你眼前一亮,通過這篇文章的詳細(xì)介紹希望你能有所收獲。
server端(單線程)
# -*- coding: cp936 -*- ''''' 建立一個(gè)python server,監(jiān)聽指定端口, 如果該端口被遠(yuǎn)程連接訪問,則獲取遠(yuǎn)程連接,然后接收數(shù)據(jù), 并且做出相應(yīng)反饋。 ''' if __name__=="__main__": import socket print "Server is starting" sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.bind(('localhost', 8001)) #配置soket,綁定IP地址和端口號(hào) sock.listen(5) #設(shè)置最大允許連接數(shù),各連接和server的通信遵循FIFO原則 print "Server is listenting port 8001, with max connection 5" while True: #循環(huán)輪詢socket狀態(tài),等待訪問 connection,address = sock.accept() try: connection.settimeout(50) #獲得一個(gè)連接,然后開始循環(huán)處理這個(gè)連接發(fā)送的信息 ''''' 如果server要同時(shí)處理多個(gè)連接,則下面的語句塊應(yīng)該用多線程來處理, 否則server就始終在下面這個(gè)while語句塊里被第一個(gè)連接所占用, 無法去掃描其他新連接了,但多線程會(huì)影響代碼結(jié)構(gòu),所以記得在連接數(shù)大于1時(shí) 下面的語句要改為多線程即可。 ''' while True: buf = connection.recv(1024) print "Get value " +buf if buf == '1': print "send welcome" connection.send('welcome to server!') elif buf!='0': connection.send('please go out!') print "send refuse" else: print "close" break #退出連接監(jiān)聽循環(huán) except socket.timeout: #如果建立連接后,該連接在設(shè)定的時(shí)間內(nèi)無數(shù)據(jù)發(fā)來,則time out print 'time out' print "closing one connection" #當(dāng)一個(gè)連接監(jiān)聽循環(huán)退出后,連接可以關(guān)掉 connection.close()
client端,每隔3秒輪番發(fā)送不同的數(shù)據(jù)給server:
if __name__=="__main__": import socket sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect(('localhost', 8001)) import time flag = '1' while True: time.sleep(3) print 'send to server with value: '+ flag sock.send(flag) print sock.recv(1024) flag = (flag=='1') and '2' or '1' #change to another type of value each time sock.close()
執(zhí)行上面兩段代碼后,可以得到如下結(jié)果:
先執(zhí)行server.py:
C:\Users\YanBo>D:\server.py Server is starting Server is listenting port 8001, with max connection 5
執(zhí)行client后:
C:\Users\YanBo>D:\client.py send to server with value: 1 welcome to server! send to server with value: 2 please go out! send to server with value: 1 welcome to server! send to server with value: 2 please go out! .....
server則相應(yīng)輸出:
Get value 1 send welcome Get value 2 send refuse .....
如果在linux下,用
$ lsof -i:8001
則可以列出正在執(zhí)行的server和client進(jìn)程,因?yàn)樗麄冋加昧硕丝?001
yanbo@yanbo-linux64-01:~$ lsof -i:8001 COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME python 2413 yanbo 3u IPv4 12907 0t0 TCP localhost:8001 (LISTEN) python 2413 yanbo 4u IPv4 12910 0t0 TCP localhost:8001->localhost:38609 (ESTABLISHED) python 2469 yanbo 3u IPv4 12222 0t0 TCP localhost:38609->localhost:8001 (ESTABLISHED)
上述內(nèi)容就是怎么在Python中利用socket發(fā)送信息,你們學(xué)到知識(shí)或技能了嗎?如果還想學(xué)到更多技能或者豐富自己的知識(shí)儲(chǔ)備,歡迎關(guān)注億速云行業(yè)資訊頻道。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。