首页 > 代码库 > day8-------socket网络编程

day8-------socket网络编程

简单的socket  一个server同时只能处理一个链接   代码如下:

 1 server端代码
 2 #author = ruixin li
 3 
 4 import socket
 5 server = socket.socket()
 6 server.bind(("0.0.0.0",5000))
 7 server.listen(5)
 8 print("开始监听")
 9 while True:
10     conn,addr = server.accept()
11     print("一个新连接")
12     print(conn,addr)
13     while True:
14         try:
15             data = http://www.mamicode.com/conn.recv(1024)
16             print("收到的信息:",data)
17             conn.send(data.upper())
18         except ConnectionResetError as e:
19             print("客户端主动断开连接")
20             break
21 server.close()
 1 客户端程序
 2 
 3 import socket
 4 
 5 
 6 cli = socket.socket()
 7 cli.connect(("localhost",5000))
 8 while True:
 9     inp = input("请输入指令:".strip())
10     if len(inp) == 0:
11         continue
12     else:
13         cli.send(inp.encode())
14         data = http://www.mamicode.com/cli.recv(1024)
15         print(data)

 

 python socket 实现简单的 ssh  命令

 1 #author  ruixin li
 2 
 3 import socket
 4 import subprocess
 5 ips = input("请输入绑定的IP:")
 6 ports = int(input("请输入绑定的端口:"))
 7 server = socket.socket()
 8 server.bind((ips,ports))
 9 server.listen(5)
10 print("开始监听")
11 while True:
12     print("跳到外部循环")
13     conn,addr = server.accept()
14     print("一个新连接")
15     print(conn,addr)
16     while True:
17         try:
18             date = conn.recv(1024)
19             if len(date) == 0:
20                 print("收到0信息,服务器主动断开连接")
21                 break
22             else:
23                 print("收到的信息:",date)
24                 msg = subprocess.Popen(date,stdout=subprocess.PIPE,stderr=subprocess.PIPE,shell=True)
25                 data =http://www.mamicode.com/ msg.stdout.read()
26                 print(data)
27                 dataerr = msg.stderr.read()
28                 print("err:",dataerr)
29                 if len(data) == 0:
30                     conn.send(dataerr)
31                 else:
32                     conn.send(data)
33         except ConnectionResetError as e:
34             print("客户端主动断开连接")
35             break
36 server.close()

客户端
 1 import socket
 2 ips = input("请输入要连接的IP:")
 3 ports = int(input("请输入要连接的端口:"))
 4 
 5 cli = socket.socket()
 6 cli.connect((ips,ports))
 7 while True:
 8     inp = input("请输入指令:".strip())
 9     if len(inp) == 0:
10         continue
11     else:
12         cli.send(inp.encode())
13         data = http://www.mamicode.com/cli.recv(1024)
14         print(data)

 

 

day8-------socket网络编程