链条传动

砥砺前行,不忘初心!

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

socketserver基本

#!/usr/bin/env python
# -*- coding: utf-8 -*-


import socket

s = socket.socket()

ip_port = ('127.0.0.1',9999)
s.connect(ip_port)

while True:
    recv_data = s.recv(1024)
    print('Server:',str(recv_data,encoding='utf-8'))
    send_data = input('Client:')
    s.send(bytes(send_data,encoding='utf-8'))
Client
#!/usr/bin/env python
# -*- coding: utf-8 -*-

import socketserver

#自定义类主要用来处理socket收发消息
class MyServer(socketserver.BaseRequestHandler):
    def handle(self):
        conn = self.request   #获取对应客户端的对象
        conn.send(bytes('Hello',encoding='utf-8'))
        while True:
            recv_data = conn.recv(1024)
            if len(recv_data) == 0:break
            send_data = str(recv_data,encoding='utf-8').upper()
            conn.send(bytes(send_data,encoding='utf-8'))







if __name__ == '__main__':
    #创建一个多线程的TCP socketserver对象。参数:ip_port、自定义类
    #每连接一个新链接,就实例化一个MyServer对象,用来处理对应链接的收发消息
    server = socketserver.ThreadingTCPServer(('127.0.0.1',9999),MyServer)
    #启动该对象
    server.serve_forever()
Server

 

socketserver之ssh交互

#!/usr/bin/env python
# -*- coding: utf-8 -*-


import socket

s = socket.socket()

ip_port = ('127.0.0.1',9999)
s.connect(ip_port)

while True:
    recv_data = s.recv(4096)
    print('Server:',recv_data.decode())
    send_data = input('Client:')
    s.send(bytes(send_data,encoding='utf-8'))
Client
#!/usr/bin/env python
# -*- coding: utf-8 -*-

import socketserver
import subprocess

#自定义类主要用来处理socket收发消息
class MyServer(socketserver.BaseRequestHandler):
    def handle(self):
        conn = self.request   #获取对应客户端的对象
        conn.send(bytes('Hello',encoding='utf-8'))
        while True:
            recv_data = conn.recv(1024)
            if len(recv_data) == 0:break

            cmd = subprocess.Popen(str(recv_data,encoding='utf-8'),shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
            cmd_res = cmd.stdout.read()   #python返回值就是字节类型
            if not cmd_res:
                cmd_res = cmd.stderr.read()
            if len(cmd_res) == 0:
                cmd_res = bytes('cmd is ok,but no return value',encoding='gbk')

            conn.send(bytes(str(cmd_res,encoding='gbk'),encoding='utf-8'))   #windows下是gbk编码







if __name__ == '__main__':
    #创建一个多线程的TCP socketserver对象。参数:ip_port、自定义类
    #每连接一个新链接,就实例化一个MyServer对象,用来处理对应链接的收发消息
    server = socketserver.ThreadingTCPServer(('127.0.0.1',9999),MyServer)
    #启动该对象
    server.serve_forever()
Server

 

socketserver之上传下载文件

#!/usr/bin/env python
# -*- coding: utf-8 -*-


import socket
import os
import json

client = socket.socket()

ip_port = ('127.0.0.1',9999)
client.connect(ip_port)

while True:
    send_data = input('Client(put/get xxx):').strip()   #上传:put xxx    下载:get xxx
    if len(send_data) == 0:
        print('输入不能为空')
        continue

    cmd_list = send_data.split()
    if len(cmd_list) < 2:
        print('输入格式错误,请重新输入')
        continue

    task_type = cmd_list[0]   #put/get
    file_path = cmd_list[1]
    if task_type == 'put':  #上传
        if os.path.isfile(file_path):   #判断是否是文件
            file_name = os.path.basename(file_path)
            file_size = os.stat(file_path).st_size   #获取文件大小
            print('文件:%s,大小:%s'%(file_name,file_size))

            # 向服务端发送操作类型(put)、文件名、文件大小
            send_msg = {'action':'put','file_name':file_name,'file_size':file_size}
            client.send(bytes(json.dumps(send_msg),encoding='utf-8'))
            recv_stat = client.recv(1024).decode()   #获取服务端准备状态
            if recv_stat == 'Ready':  #准备好了,开发发送文件
                with open(file_path,'rb') as f:
                    for line in f:
                        # print(line)
                        client.send(line)
                print('sucess!')
                break

        else:  #不是文件
            print('文件%s不存在!'%file_path)
            continue
    elif task_type == 'get':  #下载
        pass
    else:
        print('未识别的任务类型:',task_type)
        continue
Client
#!/usr/bin/env python
# -*- coding: utf-8 -*-


import socketserver
import json

class MyServer(socketserver.BaseRequestHandler):
    def handle(self):
        conn = self.request  #获取客户端对象
        while True:
            recv_msg = json.loads(conn.recv(1024).decode())
            if len(recv_msg) == 0:break
            # print('recv:',recv_msg)
            task_action = recv_msg.get('action')
            if hasattr(self,'task_%s'%task_action):   #判断类中是否存在对应字符串名的方法
                func = getattr(self,'task_%s'%task_action)  #存在,获得与字符串同名的方法
                func(recv_msg)  #将获得的数据传入该方法
                break
            else:  #方法不存在
                print('错误传入类型:',task_action)
                break

    #上传
    def task_put(self,*args,**kwargs):
        file_name = args[0].get('file_name')
        file_size = args[0].get('file_size')
        recv_size = 0
        self.request.send(bytes('Ready',encoding='utf-8'))   #告诉客户端已经准备好了

        f = open(file_name,'wb')
        while recv_size < file_size:
            recv_data = self.request.recv(1024)
            f.write(recv_data)
            recv_size += len(recv_data)
            print()
            print('文件总大小:%s,已接收数据大小:%s' % (file_size,recv_size))
        print('success!')
        f.close()


    #下载
    def task_get(self,*args,**kwargs):
        pass



if __name__ == '__main__':
    ip_port = ('127.0.0.1',9999)
    server = socketserver.ThreadingTCPServer(ip_port,MyServer)
    server.serve_forever()
Server

 

posted on 2016-12-02 14:11  链条君  阅读(245)  评论(0编辑  收藏  举报