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

客戶端 1:

 #!/usr/bin/env pythonimport socketimport osss=socket.socket(socket.AF_INET,socket.SOCK_STREAM)ss.connect(('127.0.0.1',8123)) #f=open('aa','wb')ss.sendall('hello serverdddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd')os.system('sleep 1')ss.send('EOF')data=ss.recv(1024)print "server dafu %s"%datass.close  

客戶端 2:

 #!/usr/bin/env pythonimport socketimport osss=socket.socket(socket.AF_INET,socket.SOCK_STREAM)ss.connect(('127.0.0.1',8123)) #f=open('aa','wb')ss.sendall('wokao sile')os.system('sleep 1')ss.send('FOE')data=ss.recv(1024)print "server dafu %s"%datass.close  
《Python實戰-從菜鳥到大牛的進階之路》