socket 套接字网络编程

主题:客户端可通过socket,输入系统命令,让服务端返回信息!

1.服务端代码

 1 import socket# 套接字模块
 2 import subprocess  #管道模块
 3 server_socket=socket.socket(socket.AF_INET,socket.SOCK_STREAM) #通过socket类产生一个套接字对象.
 4 server_socket.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR ,1)
 5 server_socket.bind( ("127.0.0.1",8080))#绑定
 6 server_socket.listen(5)#监听
 7 while True:#通讯循环
 8     conn,addr=server_socket.accept()
 9     while True:#链接循环
10         try:#异常处理
11             cmd=conn.recv(1024)
12             if  not cmd:break
13             res=subprocess.Popen(cmd.decode("utf-8"),
14                                  shell=True,
15                                  stderr=subprocess.PIPE,
16                                  stdout=subprocess.PIPE)
17             data=res.stderr.read()+res.stdout.read()
18             conn.send(data)
19         except Exception:
20             break
21     conn.close()
22 server_socket.close()

2.客户端代码

 1 import socket
 2 client=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
 3 client.connect(("127.0.0.1",8080))
 4 while True:
 5     cmd=input(">>>:").strip()
 6     if not cmd:break
 7     client.send(cmd.encode("utf-8"))
 8     res=client.recv(1024)
 9     print(res   .decode("gbk"))
10 client.close()
posted @ 2019-03-13 19:11  派森716  阅读(65)  评论(0编辑  收藏  举报