電腦版
首頁

搜尋 繁體

12 Python 編寫的 socket 伺服器和客戶端

熱門小說推薦

最近更新小說

伺服器端:

#!/usr/bin/pythonimport sockethost='127.0.0.1'port=8123s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)s.bind((host,port))s.listen(2)try: while True: conn,add=s.accept while True: data2='' data1=conn.recv(3) if data1=='EOF': conn.send('hello clietn1') break if data1=='FOE': conn.send('hello client2') break data2+=data1 print data2except KeyboardInterrupt: print "you have CTRL+C,Now quit" s.close

注:伺服器端一次只接收 3 個位元組的資料,我讓讀取進入迴圈,然後不斷累加到 data2 中,當讀取到 EOF 時,退出列印 data2,當讀取 FOE 時,退出列印 data2,(EOF 和 FOE 是客戶端傳送完資料時傳送的結束符),當接收到 CTRLC+C 時,關閉 socket

Loading...

未載入完,嘗試【重新整理網頁】or【關閉小說模式】or【關閉廣告遮蔽】。

使用【Firefox瀏覽器】or【Chrome谷歌瀏覽器】開啟並收藏!

移動流量偶爾打不開,可以切換電信、聯通網路。

收藏網址:www.peakbooks.cc

(>人<;)