# python socket # /usr/sbin/py/python # -*-coding:utf8-*- # python socket编程 # /usr/sbin/py/python # -*-condig:utf8-*- from socket import * server = socket(AF_INET,SOCK_STREAM) # 网络通信 TCP协议 server.setsockopt(SOL_SOCKET,SO_REUSEADDR,1) # 设置地址重用,防止下次启动报地址被占用 server.bind(("localhost",8888)) server.listen(10) # 表示可用同时接受的请求数 while True: # 为了可以接收多个连接 conn,addr = server.accept() # 需要注意的是conn是一个双向连接,一端挂了,另一端也就死掉了 print(conn,addr) while True: try: msg = conn.recv(1024) # 接受 print("接受到消息",msg.decode("utf8")) info = input("me:").strip() conn.send(info.encode("utf8")) except Exception as ex : print(ex) conn.close() break server.close() --------------------------------client---------------------------------------------------------------
# python # /usr/sbin/py/python # -*-coding:utf8-*- from socket import * client = socket(AF_INET,SOCK_STREAM) client.connect(("localhost",8888)) while True: info = input("me:").strip() client.send(info.encode("utf8")) data = client.recv(1024) print("server 回送",data.decode("utf8"))
----------------------------------------------------server循环------------------------------------------------------------------------------
# python 模拟控制台 # /usr/sbin/py/python # -*-coding:utf8-*- from socket import * import struct import subprocess server = socket(AF_INET,SOCK_STREAM) # 网络通信 TCP协议 server.setsockopt(SOL_SOCKET,SO_REUSEADDR,1) # 设置地址重用,防止下次启动报地址被占用 server.bind(("localhost",8888)) server.listen(10) # 表示可用同时接受的请求数 while True: # 为了可以接收多个连接 conn,addr = server.accept() # 需要注意的是conn是一个双向连接,一端挂了,另一端也就死掉了 print(conn,addr) while True: try: cmd = conn.recv(1024) # 接受 print("接受到消息",cmd.decode("utf8")) res = subprocess.Popen(cmd.decode("utf8"),shell=True,stderr=subprocess.PIPE, stdout=subprocess.PIPE,stdin=subprocess.PIPE) err = res.stderr.read() if not err: # 错误信息为null info = res.stdout.read() else: info = err if not info: info = "execute successful!!!".encode("gbk") # 这样直接发送会存在粘包现在 破解思路:把数据长度放到头信息中,告诉客户端,我要返回的数据长度 info_length = struct.pack("i",len(info)) # 返回的就是byte类型无需转换 i 表示封装四个字节 conn.send(info_length) # 使用这种方式 可以减少网络交互 conn.send(info) except Exception as ex : print(ex) conn.close() break server.close() -----------------------------------------------socket-------------------------------------------------------------
# python # /usr/sbin/py/python # -*-coding:utf8-*- from socket import * import struct from functools import partial client = socket(AF_INET, SOCK_STREAM) client.connect(("localhost", 8888)) def client_reveive_str(): msgl = client.recv(1024) print("/n","msg:---",msgl) if not msgl: return '' return msgl while True: info = input("me:").strip() client.send(info.encode("utf8")) # 解决粘包现象 data = client.recv(4) # 注意返回值是元组类型 print(data) length = struct.unpack("i", data)[0] recive_size = 0 recive_msg =b'' while recive_size < length: msg = client.recv(1024) if not msg: break recive_msg += msg recive_size = len(recive_msg) print("server 回送", recive_msg.decode("gbk")) # 执行控制台命令解码要和系统编码保持一致