您的位置:首页 > 理论基础 > 计算机网络

Python案例-网络编程-socket入门-server&client

2016-07-08 08:45 871 查看
废话不多说,上代码,具体逻辑分析详见注释,本次目的是实现一个单进程的ssh功能。

这是第一版单进程单任务的模型,随后还会有粘包处理、多进程以及ftp等实例

Server端

#!/usr/bin/env python
# -- coding = 'utf-8' --
# Author Allen Lee
# Python Version 3.5.1
# OS Windows 7

import 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:break
print(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()
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息