socket流程
基础版功能
server 端
import socket server = socket.socket(socket.AF_INET,socket.SOCK_STREAM)#ipv4,tcp # Socket Families(地址簇) # socket.AF_UNIX unix本机进程间通信 # socket.AF_INET IPV4 # socket.AF_INET6 IPV6 # Socket Types # socket.SOCK_STREAM #for tcp # socket.SOCK_DGRAM #for udp # socket.SOCK_RAW #原始套接字,普通的套接字无法处理ICMP、IGMP等网络报文,而SOCK_RAW可以; # 其次,SOCK_RAW也可以处理特殊的IPv4报文;此外,利用原始套接字,可以通过IP_HDRINCL套接字选项由用户构造IP头。 # socket.SOCK_RDM #是一种可靠的UDP形式,即保证交付数据报但不保证顺序。SOCK_RAM用来提供对原始协议的低级访问, # 在需要执行某些特殊操作时使用,如发送ICMP报文。SOCK_RAM通常仅限于高级用户或管理员运行的程序使用。 server.bind(("0.0.0.0",8000)) #绑定ip,端口 server.listen(5) #监听5个 print("-----------------start to listen.....") conn,client_addr = server.accept() #等待 conn 链接的标记位; client_addr的链接地址 #conn就是客户端链接过来而在服务器端为其生成的一个连接实例 # print(conn,client_addr) while True: data = conn.recv(1024) print("recv from cli:",data.decode()) conn.send("got your mes".encode()) server.close()
client端
import socket client = socket.socket() #声明socket类型,同时生成socket链接对象 client.connect(("localhost",8000)) while True: msg = input(">>:").strip() if len(msg) == 0:continue #如果不写会卡住 client.send(msg.encode("utf-8")) #转成utf-8 print("send",msg) # data = client.recv(1024) #1024byte # print("receive from server:",data.decode()) client.close()
无限录入版
server
import socket,subprocess server = socket.socket(socket.AF_INET,socket.SOCK_STREAM)#ipv4,tcp server.bind(("0.0.0.0",8000)) #绑定ip,端口 server.listen(5) #监听5个 print("-----------------start to listen.....") while True: conn,client_addr = server.accept() #等待 conn 链接的标记位; client_addr的链接地址 #conn就是客户端链接过来而在服务器端为其生成的一个连接实例 # print(conn,client_addr) while True: data = conn.recv(1024) #接过来的命令 res_obj = subprocess.Popen(data,shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE) res = res_obj.stdout.read() conn.send(str(len(res)).encode()) conn.send(res) server.close()
client
import socket client = socket.socket() #声明socket类型,同时生成socket链接对象 client.connect(("localhost",8000)) while True: msg = input(">>:").strip() if len(msg) == 0:continue #如果不写会卡住 client.send(msg.encode()) #转成utf-8 print("send",msg) data = client.recv(1024) #1024byte print("receive from server:",data.decode()) total_size = int(data.decode()) received_size = 0 res = b‘‘ while received_size < total_size: d = client.recv(1024) res += d received_size += len(d) print("--------rece done--------") print(res.decode()) client.close()
时间: 2024-09-28 22:52:56