zoukankan      html  css  js  c++  java
  • Python socket学习笔记(二)

    Socket 例子

    server端

    import  socket
    HOST = ''    
    PORT = 50007
    s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
    s.bind((HOST,PORT))
    s.listen(1)
    conn,addr = s.accept()
    
    print ('Connected by ',addr)
    
    while 1:
        data=conn.recv(1024)
        if not data:break
        conn.sendall(data)
    conn.close()

    clinet 端

    import socket
    HOST = '10.2.34.207'  #server's IP
    PORT = 50007          #server's port
    s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
    s.connect((HOST,PORT))
    
    s.sendall('Hello World')
    data = s.recv(1024)
    s.close()
    print ('Received',repr(data))

    效果演示

    缺点:只能通信一次,下一步持续通信

    服务器端:

    import  socket
    HOST = ''
    PORT = 50007
    s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
    s.bind((HOST,PORT))
    s.listen(1)

    while 1:
    conn, addr = s.accept()
    print ('Connected by ', addr)
    data=conn.recv(1024)
    if not data:break
    print('data from :',addr,data)
    conn.sendall(data)
    conn.close()

    效果演示:

    下一步长连接设置:

    修改client代码:

    import  socket
    HOST = ''
    PORT = 50007
    s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
    s.bind((HOST,PORT))
    s.listen(1)

    while 1:
    conn, addr = s.accept()
    print ('Connected by ', addr)

    while 1:
    data=conn.recv(1024)
    if not data:break
    print('data from :',addr,data)
    conn.sendall(data)
    conn.close()

    模拟 ssh协议

    服务器

    import socket,commands
    HOST = ''
    PORT = 50007
    s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
    s.bind((HOST,PORT))
    s.listen(4)

    while 1:
    conn, addr = s.accept()
    print ('Connected by ', addr)

    while 1:
    data=conn.recv(1024)

    if not data:break
    print('Command received from :',addr,data)
    cmd_status,result = commands.getstatusoutput(data)

    if cmd_status == 0:
    conn.sendall(result)
    else:
    conn.sendall("DONE")
    conn.close()


    客户端:

    import socket,time,sys

    
    

    HOST = 'localhost' #server's IP
    PORT = 50007 #server's port

    
    

    s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
    s.connect((HOST,PORT))

    
    

    while 1:
    cmd = raw_input("The command,e for exit:").strip()
    if len(cmd) == 0: continue
    elif cmd == 'e': sys.exit()
    s.sendall(cmd)
    data = s.recv(1024)
    #time.sleep(2)
    print (data)
    s.close()

     

    演示效果

      解决了错误命令,客户端退出,空输入 等问题

  • 相关阅读:
    接竹竿
    Vijos P1053 Easy SSSP
    计算机网络-五层协议和物理层
    代码阅读
    selenium自动化测试原理和设计的分享
    appium desktop 1.7 byName不能用,重写
    appium desktop 1.7 的swipe功能不能用,重写。
    appium在不同类中使用的是同一个session
    GIT 上传、ssh设置、一些命令。
    java 学习:在java中启动其他应用,由jenkins想到的
  • 原文地址:https://www.cnblogs.com/bxhsdy/p/13329632.html
Copyright © 2011-2022 走看看