马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。
您需要 登录 才可以下载或查看,没有账号?立即注册
x
本帖最后由 骑单车的小女孩 于 2016-12-30 00:44 编辑
目前处在学习python的阶段,昨天看到了python的socket模块,分别实现TCP、UDP时间戳回显。- # 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()
复制代码- #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()
复制代码
|