1TCP Socketserver
服务器
import socketserver
class MyServer(socketserver.BaseRequestHandler):
def handle(self):
while True:
msg = self.request.recv(1024).decode("utf-8")
self.request.send(msg.upper().encode("utf-8"))
server =socketserver.ThreadingTCPServer(("127.0.0.1",9090),MyServer)
server.serve_forever()
客户端
from socket import *
client =socket(AF_INET,SOCK_STREAM)
client.connect(("127.0.0.1",9090))
while True:
x = input("向服务器发送:").strip()
if not x :continue
client.send(x.encode("utf-8"))
msg = client.recv(1024).decode("utf-8")
print(msg)
1.1UDP Socketserver
服务器
import socketserver
class MyUdp(socketserver.BaseRequestHandler):
def handle(self):
print(self.request)
data = self.request[0]
print("客户端发来的数据",data.decode("utf-8"))
self.request[1].sendto(data.upper(),self.client_address)
server = socketserver.ThreadingUDPServer(("127.0.0.1",8989),MyUdp)
server.serve_forever()
客户端
from socket import *
client =socket(AF_INET,SOCK_DGRAM)
address = ("127.0.0.1",8989)
while True:
x = input("向服务器发送:").strip()
if not x :continue
client.sendto(x.encode("utf-8"),address)
msg,add = client.recvfrom(1024)
print(msg.decode("utf-8"))
2Event
"""
事件是什么?
某件事情发生的信号
用来干什么?
在线程间通讯 然而线程本来就能通讯
作用只有一个就是简化代码
线程间通讯的例子
服务器启动需要五秒
客户端启动后去连接服务器
去连接服务器必须保证服务器已经开启成功了
是否启动完成就是要通讯的内容
注意 Event线程通讯 仅仅用于简单的条件判断 说白了代替bool类型 和if判断
set() 将状态修改为True
wati() 等待状态为True才继续执行
"""
# import time
# from threading import Thread
# boot = False
# def server_task():
# global boot
# print("正在启动....")
# time.sleep(5)
# print("启动....成功")
# boot = True
#
# def client_task():
# while True:
# print("连接服务器....")
# time.sleep(1)
# if boot:
# print("连接成功")
# break
# else:
# print("error 连接失败 服务器未启动!!")
#
# t1 = Thread(target=server_task)
# t1.start()
#
# t2 = Thread(target=client_task)
# t2.start()
#
# t1.join()
# t2.join()
# 使用事件实现
import time
from threading import Thread,Event
event =Event()
def server_task():
print("正在启动....")
time.sleep(5)
print("启动....成功")
event.set()
def client_task():
event.wait() #一个阻塞的函数 会阻塞直到对event执行set函数为止
print("连接成功!")
t1 = Thread(target=server_task)
t1.start()
t2 = Thread(target=client_task)
t2.start()