Python 网络编程(一)
2012-10-11 17:22 AlexDotNet 阅读(196) 评论(0) 编辑 收藏 举报TCP/IP 之间socket 之间的通信 通过代码 来比较两者之间的区别
socket(socket_family,socket_type,protocol=0)
tcpSock=socket.socket(socket.AF_INET,socket.SOCK_STREAM) --->创建tcp的套接字
udpSock=socket.soceket(socket.AF_INET,socket.SOCK_DGRAM)--->创建udp的套接字
先看TCP/Server
from socket import * from time import ctime HOST='' PORT=770 BUFSIZ=1024 ADDR=(HOST,PORT) tcpSerSock=socket(AF_INET,SOCK_STREAM) tcpSerSock.bind(ADDR) tcpSerSock.listen(5) while True: print 'waiting for connectiong....' tcpCliSock=tcpSerSock.accept() print '....connected form:', tcpCliSock while True: data=tcpCliSock.recv(BUFSIZ) if not data: break tcpCliSock.send('[%s] %s' % (ctime(),data)) tcpCliSock.close() tcpSerSock.close()
Client
from socket import * HOST='localhost' PORT=770 BUFSIZ=1024 ADDR=(HOST,PORT) tcpCliSock=socket(AF_INET,SOCK_STREAM) tcpCliSock.connect(ADDR) while True: data=raw_input('>') if not data: break tcpCliSock.send(data) data=tcpCliSock.recv(BUFSIZ) if not data: break print data tcpCliSock.close()
记录一下UDP/IP 协议下的简单通信
Client端
from socket import * HOST='localhost' PORT=700 BUFSIZ=1024 ADDR=(HOST,PORT) udpCliSock=socket(AF_INET,SOCK_DGRAM) while True: data=raw_input('> ') if not data: break udpCliSock.sendto(data,ADDR) data,ADDR=udpCliSock.recvfrom(BUFSIZ) if not data: break print data udpCliSock.close() udpCliSock.close()
服务端
from socket import * from time import ctime HOST='' PORT=700 BUFSIZ=1024 ADDR=(HOST,PORT) udpSerSock=socket(AF_INET,SOCK_DGRAM) udpSerSock.bind(ADDR) while True: print 'waiting for meassage' data,addr=udpSerSock.recvfrom(BUFSIZ) udpSerSock.sendto('[%s] %s' %(ctime(),data),addr) print '......recevied from and returned to:',addr updSerSock.close()