在python socket編程主要是面各tcp 和 udp編程。下面我們就用這兩種不同的編程方式來實現一個從客服端發送資訊到伺服器端,
伺服器端返回客服器現在時間和接收到的資訊
我們先來實現tcp的編程
tcp 服務端代碼(tsTserv.py):
'''<br />Created on 2010-12-13<br />@author: Administrator<br />'''<br />from socket import *<br />from time import ctime<br />HOST=''<br />PORT=21582<br />BUFSIZ=1024<br />ADDR=(HOST,PORT)<br />tcpSerSock=socket(AF_INET,SOCK_STREAM)<br />tcpSerSock.bind(ADDR)<br />tcpSerSock.listen(5)<br />while True:<br /> print 'waiting for connection...'<br /> tcpCliSock,addr=tcpSerSock.accept()<br /> print '...connected from:',addr</p><p> while True:<br /> data=tcpCliSock.recv(BUFSIZ)<br /> if not data:<br /> break<br /> tcpCliSock.send('[%s] %s' %(ctime(),data))<br /> tcpSerSock.close()<br /> tcpCliSock.close()<br />
tcp客服端代碼(tsTclnt.py):
'''<br />Created on 2010-12-13<br />@author: Administrator<br />'''<br />from socket import *<br />HOST='localhost'<br />PORT=21582<br />BUFSIZ=1024<br />ADDR=(HOST,PORT)<br />tcpCliSock=socket(AF_INET,SOCK_STREAM)<br />tcpCliSock.connect(ADDR)<br />while True:<br /> data=raw_input('>')<br /> if not data:<br /> break<br /> tcpCliSock.send(data)<br /> data=tcpCliSock.recv(BUFSIZ)<br /> if not data:<br /> break<br /> print data<br />tcpCliSock.close()<br />
ok 我們現在來看下:
實現upd 編程
udp服務端代碼(tsUserv.py):
'''<br />Created on 2010-12-13<br />@author: Administrator<br />'''<br />from socket import *<br />from time import ctime<br />HOST=''<br />PORT=21590<br />BUFSIZ=1024<br />ADDR=(HOST,PORT)<br />udpSerSock=socket(AF_INET,SOCK_DGRAM)<br />udpSerSock.bind(ADDR)<br />while True:<br /> print 'waiting for message...'<br /> data,addr=udpSerSock.recvfrom(BUFSIZ)<br /> udpSerSock.sendto('[%s] %s' %(ctime(),data),addr)<br /> print '...received from and returned to:',addr<br /> udpSerSock.close()</p><p>
udp 客服端代碼(tsUclnt.py):
'''<br />Created on 2010-12-13<br />@author: Administrator<br />'''<br />from socket import *<br />from time import ctime<br />HOST='localhost'<br />PORT=21590<br />BUFSIZ=1024<br />ADDR=(HOST,PORT)<br />udpCliSock=socket(AF_INET,SOCK_DGRAM)<br />while True:<br /> data=raw_input('>')<br /> if not data:<br /> break<br /> print data<br /> udpCliSock.sendto(data,ADDR)<br /> data,ADDR=udpCliSock.recvfrom(BUFSIZ)<br /> if not data:<br /> break<br /> print data<br />udpCliSock.close()<br />
ok 完成,來看下