Python的socket编程
2018-07-20 来源:open-open
目前处在学习python的阶段,昨天看到了python的socket模块,分别实现TCP、UDP时间戳回显。
1、tcp通信server和client代码
# tcpServer.py #!/usr/bin/python # -*- coding: utf-8 -*- from socket import * from time import ctime HOST = '' PORT = 21156 BUFSIZE = 1024 ADDR = (HOST,PORT) tcpServerSock = socket(AF_INET,SOCK_STREAM) tcpServerSock.bind(ADDR) tcpServerSock.listen(5) while True: print 'waiting for connection...' tcpClientSock ,addr = tcpServerSock.accept() print '...connected from:',addr while True: data=tcpClientSock.recv(BUFSIZE) if not data: break tcpClientSock.send('[%s] %s' % (ctime(),data)) tcpClientSock.close() tcpServerSock.close
# tcpClient.py #!/usr/bin/python # -*- coding: utf-8 -*- from socket import * HOST = 'localhost' PORT = 21156 BUFSIZE = 1024 ADDR = (HOST,PORT) tcpClientSock = socket(AF_INET,SOCK_STREAM) tcpClientSock.connect(ADDR) while True: data = raw_input('>') if not data: break tcpClientSock.send(data) data = tcpClientSock.recv(BUFSIZE) if not data: break print data tcpClientSock.close()
2、udp通信server和client代码
#udpServer.py #!/usr/bin/python # -*- coding: utf-8 -*- from socket import * from time import ctime HOST = '' PORT = 21156 BUFSIZE = 1024 ADDR = (HOST,PORT) udpServerSock = socket(AF_INET,SOCK_DGRAM) udpServerSock.bind(ADDR) while True: print 'waiting for message...' data ,addr = udpServerSock.recvfrom(BUFSIZE) udpServerSock.sendto('[%s] %s' % (ctime(),data), addr) print '...received from and returned to:',addr tcpClientSock.close() tcpServerSock.close
#udpClient.py #!/usr/bin/python # -*- coding: utf-8 -*- from socket import * # from time import ctime HOST = 'localhost' PORT = 21156 BUFSIZE = 1024 ADDR = (HOST,PORT) udpClientSock = socket(AF_INET,SOCK_DGRAM) while True: data = raw_input('>') if not data: break udpClientSock.sendto(data,ADDR) data,ADDR = udpClientSock.recvfrom(BUFSIZE) if not data: break print data udpClientSock.close()
版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点!
本站所提供的图片等素材,版权归原作者所有,如需使用,请与原作者联系。
上一篇:Java版 数字金额大写转换
最新资讯
热门推荐