目前处在学习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()
标签:ADDR,Python,编程,PORT,HOST,data,tcpClientSock,socket From: https://www.cnblogs.com/q-q56731526/p/17355049.html