# >>>>>>>>>>>>>>>>>>>>服务端socketserver模块通讯循环>>>>>>>>>>>>>>
import socketserver
class MyHandler(socketserver.BaseRequestHandler):
def handle(self):#通过对象调用handle方法,方法名一个字都不能改
while True:
# 通信循环
try:
#self.request相当于conn
# print(self.client_address)
# print(self.request) #self.request=conn
data=self.request.recv(1024)
if len(data)==0:break
self.request.send(data.upper())
except ConnectionResetError:
break
if __name__=='__main__':
#额,bind_and_activate相当于bind 和listen
s=socketserver.ThreadingTCPServer(('127.0.0.1',8080),MyHandler,bind_and_activate=True)
#这里拿到一个socketserver的对象
s.serve_forever()#代表连接循环
# 循环建立连接,每建立一个连接就会启动一个线程(服务员)+调用Myhandler类产生一个对象,调用该对象下的handle方法,专门与刚刚建立好的连接做通信循环
# >>>>>>>TCP协议的客户端
import socket ,time
phone=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
phone.connect(('127.0.0.1',8080))#指定服务端的IP 的端口
while True:
time.sleep(1)
msg='client23223'
if len(msg)==0:continue
phone.send(msg.encode('utf-8'))
data=phone.recv(1024)
print(data)
phone.close()
# ..........................end....................
# >>>>>>>>>>>>>>>>>>>>>>>>>socketsever基于UDP通讯的服务端>>>>>>>>>>>
import socketserver
class MyHandler(socketerver.BaserequestHandler):
def handle(self):
#通讯循环
#print(self.client_address)
#这里的结果为客户端的IP和端口
#print(self.request)
#结果为一个元组有两个参数,第一个是收到的客户端的内容,第二个是socket的套接字对象
data=self.request[0]
print('客户消息',data)
self.request[1].sendto(data.upper(),self.client_address)
if __name__ == '__main__':
s=sockserver.ThreadingUDPServer(('127.0.0.1',8080),MyHandler)
s.serve_forever()#永远建立链接
# >>>>>>>>>>>>>>>>>>>>>>>>>>客户端>>>>>>>>>>>>>>>>>>>
import socket
client=socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
while True:
msg='client444444444'
client.sendto(msg.encode('utf-8'),('127.0.0.1',8080))
data.server_addr=client.recvfrom(1024)
client.close()