标签:ftp 实例 ever request 处理 import nec tcp eve
基于socketserver实现并发的socket编程
基于tcp的套接字,关键就是两个循环,一个链接循环,一个通信循环
socketserver模块中分两大类:server类(解决链接问题)和request类(解决通信问题)
[
[
[
[
[
# 使用socketserver写服务端
# 导入模块
import socketserver
# 自己定义一个类, 必须继承BaseRequestHandler
class Mytcp(socketserver.BaseRequestHandler):
# 必须要重写handle方法
def handle(self):
while True: # 通信循坏
print(self)
# 给客户端回消息
print(self.request)
print(self.client_address)
# 接收数据, conn对象就是request
data = self.request.recv(1024)
print(data)
if len(data) == 0:
return
# 发送数据
self.request.send(b'234')
if __name__ == '__main__':
# 实例化得到一个tcp连接对象, Threading意思是说,只要来了请求,他就自动开线程来处理连接跟交互数据
# 第一个参数是绑定的地址, 第二个参数传一个类
server = socketserver.ThreadingTCPServer(('127.0.0.1',8009), Mytcp)
# 一直监听
# 可以这么理解:只要来一个请求, 就起一个线程(连接一个人, 做交互)
server.serve_forever()
import socket
phone = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
phone.connect(('127.0.0.1', 8080)) # 指定服务端ip和端口
while True:
# msg=input('>>: ').strip() #msg=''
msg = 'client33333' # msg=''
if len(msg) == 0: continue
phone.send(msg.encode('utf-8'))
data = phone.recv(1024)
print(data)
phone.close()
import socket
phone = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
phone.connect(('127.0.0.1', 8080)) # 指定服务端ip和端口
while True:
# msg=input('>>: ').strip() #msg=''
msg = 'client11111' # msg=''
if len(msg) == 0: continue
phone.send(msg.encode('utf-8'))
data = phone.recv(1024)
print(data)
phone.close()
import socketserver
class MyUdp(socketserver.BaseRequestHandler):
def handle(self):
# print(self.request)
# data=self.request[0]
# print(data)
data, addr = self.request[1].recvfrom(1024)
print(data)
self.request[1].sendto('xxxx'.encode('utf-8'),addr)
# self.request[1].sendto('xxxx'.encode('utf-8'),self.client_address)
# while True:
# try:
# data = self.request.recvfrom(1024)
# print(data)
# # self.request.sendto(b'123')
#
# except Exception as e:
# print(e)
# break
if __name__ == '__main__':
server = socketserver.ThreadingUDPServer(('127.0.0.1', 8010), MyUdp)
server.serve_forever()
import socket
client=socket.socket(type=socket.SOCK_DGRAM)
client.sendto('randy'.encode('utf-8'),('127.0.0.1', 8010))
data = client.recvfrom(1024)
print(data)
import socket
client = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # 数据报协议-》udp
while True:
# msg=input('>>: ').strip() #msg=''
msg = 'client2222'
client.sendto(msg.encode('utf-8'), ('127.0.0.1', 8080))
data, server_addr = client.recvfrom(1024)
print(data)
client.close()
ftpserver=socketserver.ThreadingTCPServer(('127.0.0.1', 8080),FtpServer)
ftpserver.serve_forever()
查找属性的顺序:ThreadingTCPServer->ThreadingMixIn->TCPServer->BaseServer
基于tcp的socketserver我们自己定义的类中的
基于udp的socketserver我们自己定义的类中的
标签:ftp 实例 ever request 处理 import nec tcp eve
原文地址:https://www.cnblogs.com/randysun/p/11517086.html