socket作业

作业一:
整理博客
预习基于udp的套接字

作业二:
基于tcp的套接字实现远程执行命令的操作

import socket
import subprocess
phone=socket.socket(socket.AF_INET,socket.SOCK_STREAM) #买手机
phone.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)
phone.bind(('127.0.0.1',8081)) #绑定手机卡

phone.listen(5) #开机

while True:
    conn,addr=phone.accept() #等待电话链接
    print('电话线路是',conn)
    print('客户端手机号是',addr)
    while True: #通信循环
        try:
            data=conn.recv(1024) #收消息 ?1024
            print('客户端发来的消息是',data)
            res=subprocess.Popen(data.decode("utf8"),shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
            correct_info=res.stdout.read()
            error_info=res.stderr.read()
            if not error_info:
                conn.send(correct_info)
            else:
                conn.send(error_info)
        except Exception:
            break
    conn.close()

phone.close()
服务端
import socket
phone=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
phone.connect(('127.0.0.1',8081))

while True:
    msg=input('>>:').strip()
    if not msg:continue
    phone.send(msg.encode('utf-8'))
    data=phone.recv(1024)
    print(data.decode("gbk"))
phone.close()
客户端
import socket
import subprocess
phone=socket.socket(socket.AF_INET,socket.SOCK_STREAM) #买手机
phone.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)
phone.bind(('127.0.0.1',8081)) #绑定手机卡

phone.listen(2) #开机

while True:
    conn,addr=phone.accept() #等待电话链接
    print('电话线路是',conn)
    print('客户端手机号是',addr)
    while True: #通信循环
        try:
            data=conn.recv(1024) #收消息 ?1024
            print('客户端发来的消息是',data)
            res=subprocess.Popen(data.decode("utf8"),shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
            correct_info=res.stdout.read()
            error_info=res.stderr.read()
            conn.send(correct_info)
            conn.send(error_info)
        except Exception:
            break
    conn.close()

phone.close()
服务端升华版

作业三:
面向对象小组分享准备

posted @ 2017-05-03 16:51  luchuangao  阅读(143)  评论(0编辑  收藏  举报