当前位置: 代码迷 >> 综合 >> Python案例-网络编程-socket入门-serverclient
  详细解决方案

Python案例-网络编程-socket入门-serverclient

热度:65   发布时间:2023-09-19 14:04:08.0

废话不多说,上代码,具体逻辑分析详见注释,本次目的是实现一个单进程的ssh功能。
这是第一版单进程单任务的模型,随后还会有粘包处理、多进程以及ftp等实例

Server端

#!/usr/bin/env python
# -- coding = 'utf-8' --
# Author Allen Lee
# Python Version 3.5.1
# OS Windows 7import subprocess,socket,socketserver
#服务端:
#准备工作:初始化服务器 ip和端口,以元组形式
ip_port = ('127.0.0.1',1314)
#第一步:创建服务端对象
server = socket.socket()#第二步:绑定ip和端口
server.bind(ip_port)#第三步:启动服务器,,并传递一个数字,这个数字代表服务对大可接受挂起的client数
server.listen(1)#第四步:等待接收client发起的请求(阻塞状态)
#此处循环为了让一个client访问结束后,在重新创建session等待下一个client
while True:conn,addr = server.accept()print(addr)#第五步:接收client发出的信息,recv必须传入一个数字参数,定义最小接收数据单元大小#次循环是为了进行异常处理while True:try:res_data = conn.recv(1024)if len(res_data) == 0:breakprint(res_data,type(res_data))p = subprocess.Popen( str(res_data,encoding = 'utf-8'),shell = True,stdout = subprocess.PIPE )res = p.stdout.read()if len(res) == 0:sendfile = 'cmd_err'else:sendfile = str(res,encoding='gbk')print(send_file)#send_file = res_msg.upper()#第六步:给client回包#由于socket的recv只接受bytes类型,因此在发送时需要转码conn.send(bytes(send_file,encoding='utf-8'))except Exception:break#第七步:完成交互,结束会话conn.close()

Client端:

#!/usr/bin/env python
# -- coding = 'utf-8' --
# Author Allen Lee
# Python Version 3.5.1
# OS Windows 7
import socket,subprocess
#客户端:
#创建目标服务器ip和端口
ip_port = ('127.0.0.1',1314)
#第一步:创建socket对象
client = socket.socket()#第二步:连接目标服务器的端口和ip
client.connect(ip_port)#第三步:发送信息
#循环,如果用户输入空内容,则返回重新输入
while True:send_file = input('>>: ').strip()#设置主动断开的开关if send_file == 'exit':break#判断如果为空则跳出本次循环,让用户重新输入if len(send_file) == 0:continue#socket的recv方法只能接受bytes数据类型,因此需要bytes对input信息以utf-8解码client.send(bytes(send_file,encoding='utf-8'))#第四步:收服务端回复的包res_msg = client.recv(1024)print(str(res_msg,encoding='utf-8'))
#第五步:结束本次会话
client.close()
  相关解决方案