Python編寫的Socket服務器和客戶端
服務器端:
#!/usr/bin/python
import socket
host='127.0.0.1'
port=8123
s=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 data2
except 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 python
import socket
import os
ss=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"%data
ss.close()
客戶端2:
#!/usr/bin/env python
import socket
import os
ss=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"%data
ss.close()