zoukankan      html  css  js  c++  java
  • 网络编程杂项2

    import socket #模块导入
    import subprocess
    sk = socket.socket() #创建套接字
    sk.bind(('127.0.0.1',8000)) #绑定ip 端口
    sk.listen(5)

    while True: #循环接受用户请求
    conn,addr = sk.accept() #接受用户信息和ip地址
    while True:
    try:
    cmd = str(conn.recv(1024),'utf-8') #把用户信息接受utf-8
    if cmd: #判断是否为空
    print('>>>:',cmd) #服务端打印命令
    obj = subprocess.Popen(cmd,shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
    #调用Popen类相当于终端把,cmd命令,shell=True设置异常,最好为真,stdout或stderr标准正确输出和错误输出
    if not obj.wait():#等待子进程返回0 或 不正常
    cmd_result = obj.stdout.read()
    #正常情况下接受执行结果
    else:
    print('错误:')#否则错误
    cmd_result = obj.stderr.read()
    #接受错误信息
    print(str(cmd_result,'gbk'))
    #在服务器端打印错误信息
    result_len = bytes(str(len(cmd_result)),'utf-8')
    #获取结果的长度
    conn.send(result_len)#结果的长度发送给客户端
    conn.recv(1024) #防止黏包,一根面条剪一下,是不是就不会黏在一起了
    conn.sendall(cmd_result)#把执行结果发送给客户端
    else:
    conn.close() #客户端退出,则关闭这个连接,退出循环等待下个连接
    break

    except ConnectionRefusedError as e: #防止客户异常退出,打印异常退出循环,监听下个
    print(e)
    break
    import socket #模块
    sk = socket.socket() #套接字
    sk.connect(('127.0.0.1',8000)) #ip地址 端口
    while True: #循环发送消息
    cmd = input('>>>:').strip() #命令,.strip()去除换行空格
    if cmd == 'exit': #exit退出连接
    sk.close()
    break
    sk.send(bytes(cmd,'utf-8'))#命令以utf-8字符格式并以二进制格式发送过去
    result_len = int(str(sk.recv(1024),'utf-8'))
    #接受服务器发送结果的长度
    sk.send(bytes('ok','utf-8'))
    #防止数据粘连
    print(result_len)
    date = bytes() #二进制格式来接受执行结果
    while len(date) != result_len: #循环接受结果
    date += sk.recv(1024)
    print(str(date,'gbk')) #打印结果
  • 相关阅读:
    WCF Server Console
    Restart IIS With Powershell
    RestartService (recursively)
    Copy Files
    Stopping and Starting Dependent Services
    多线程同步控制 ManualResetEvent AutoResetEvent MSDN
    DTD 简介
    Using Powershell to Copy Files to Remote Computers
    Starting and Stopping Services (IIS 6.0)
    java中的NAN和INFINITY
  • 原文地址:https://www.cnblogs.com/lc1013/p/10231094.html
Copyright © 2011-2022 走看看