12 python 編寫的 socket 服務器和客戶端
Python實戰-從菜鳥到大牛的進階之路 作者:極客學院 投票推薦 加入書簽 留言反饋
服務器端:
#!/usr/bin/pythonimport sockethost=''127.0.0.1''port=8123s=socket.socket(socket.af_,socket.sock_stream)s.bind((host,port))s.listen(2)try: while true: conn,add=s.ept 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 </pre>
注:服務器端一次隻接收 3 個字節的數據,我讓讀取進入循環,然後不斷累加到 data2 中,當讀取到 eof 時,退出打印 data2,當讀取 foe 時,退出打印 data2,(eof 和 foe 是客戶端發送完數據時發送的結束符),當接收到 ctrlc+c 時,關閉 socket
客戶端 1:
#!/usr/bin/env pythonimport socketimport osss=socket.socket(socket.af_,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 </pre>
客戶端 2:
#!/usr/bin/env pythonimport socketimport osss=socket.socket(socket.af_,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 </pre>
#!/usr/bin/pythonimport sockethost=''127.0.0.1''port=8123s=socket.socket(socket.af_,socket.sock_stream)s.bind((host,port))s.listen(2)try: while true: conn,add=s.ept 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 </pre>
注:服務器端一次隻接收 3 個字節的數據,我讓讀取進入循環,然後不斷累加到 data2 中,當讀取到 eof 時,退出打印 data2,當讀取 foe 時,退出打印 data2,(eof 和 foe 是客戶端發送完數據時發送的結束符),當接收到 ctrlc+c 時,關閉 socket
客戶端 1:
#!/usr/bin/env pythonimport socketimport osss=socket.socket(socket.af_,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 </pre>
客戶端 2:
#!/usr/bin/env pythonimport socketimport osss=socket.socket(socket.af_,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 </pre>