day02-tcp-CS框架
2022-01-25 本文已影响0人
落入粪池的凤凰
流程图
tcp.jpg代码区
Client
def tcp_client():
try:
tcp_socket = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
tcp_socket.connect(("10.1.50.131",8282))
t = time.strftime("%H:%M:%S",time.localtime())
send_data(soc=tcp_socket,data=t)
#20秒后关闭连接
# threading.Thread(target=close_tcp_client)
#一直循环接受tcp服务器的消息
while 1:
receive_data = tcp_socket.recv(10240)
print(str(receive_data, 'utf-8'))
time.sleep(2)
tcp_socket.send(receive_data)
except BaseException:
print(error)
ESSendData = Union[Any, str]
def send_data(soc:socket.socket,data:str = ...,):
encode_data = data.encode("utf-8")
soc.send(encode_data)
def close_tcp_client(soc:socket.socket):
time.sleep(20)
soc.close()
if __name__ == "__main__":
tcp_client()
service
from concurrent.futures import thread
from distutils.log import error
from json.tool import main
import socket
import time
from typing import Any, Union
import threading
def tcp_service():
#这个socket仅仅用于监听,不进行通讯,通讯的socket是通过accept来返回新的socket
tcp_service = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
tcp_service.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,True)
tcp_service.bind(("10.1.50.131",8282))
#最大监听数
tcp_service.listen(128)
while 1:
#返回元组,client_socket(和客户端通讯的socket)、client_address = (IP,port) 客户端的地址
client_socket,client_address = tcp_service.accept()
#新建一个线程用于接收新的消息
sub_recv = threading.Thread(target=recv,args=(client_socket,))
sub_recv.start()
def recv(client_socket):
while 1:
data = client_socket.recv(1024)
print(data.decode("utf-8"))
time.sleep(2)
client_socket.send(data)
if len(data) == 0 :
print("客户端已经断开")
break
if __name__ == "__main__":
tcp_service()