代码之家  ›  专栏  ›  技术社区  ›  user7693832

如何在python中关闭套接字连接?

  •  0
  • user7693832  · 技术社区  · 7 年前

    我有socket server和socket client两个端程序:

    服务器:

    #!/usr/bin/env python3
    #-*- coding:utf-8 -*-
    # Author:sele
    
    
    import socket
    
    HOST = '127.0.0.1'
    PORT = 65432
    
    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
        s.bind((HOST, PORT))
        s.listen()
        conn, addr = s.accept()
        with conn:
            print('Connected by', addr)
    
            if addr and addr[0] != '127.0.0.44':
                conn.sendall(b'ip error')  # there I want to cut off the socket connection.
    
            else:
    
                while True:
                    data = conn.recv(1024)
                    if not data:
                        break
    
                    conn.sendall(data)
    

    #!/usr/bin/env python3
    #-*- coding:utf-8 -*-
    # Author:lele
    
    import socket
    
    HOST = '127.0.0.1'
    PORT = 65432
    
    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
        s.connect((HOST, PORT))
        s.sendall(b'Hello, world')
        data = s.recv(1024)
    
    print('Received', repr(data))
    

    if addr and addr[0] != '127.0.0.44': 那里我想关闭连接,怎么办?

    conn.close() 那个地方的密码?

    连接关闭() ,则服务器现在似乎停止运行:

    sele-MacBook-Pro:test01 ldl$ ./tests02-server.py 
    Connected by ('127.0.0.1', 53321)
    sele-MacBook-Pro:test01 ldl$ 
    
    1 回复  |  直到 7 年前
        1
  •  2
  •   Jeremy Friesner    7 年前

    打电话 conn.close()

    因为我试过使用连接关闭(),则服务器现在似乎停止运行:

    对,因为这就是你编程服务器要做的。特别是,客户端关闭连接会导致 conn.recv(1024) 返回 None ,这会导致if测试成功,然后 break 将服务器从while循环中断开,然后服务器从while循环中退出,因为没有其他循环可供它执行。

            while True:
                data = conn.recv(1024)
                if not data:
                    break
    

    while True: 循环从 s.accept() 行,即:

    while True:
       conn, addr = s.accept()
       with conn:
           print('Connected by', addr)
           [...]