客户端连接后,套接字连接立即丢失

时间:2018-06-07 22:58:50

标签: python networking ip

我对Python完全陌生。我正在研究由其他人编写的脚本中的问题,其中它创建了一个套接字并开始侦听客户端连接。我告诉问题是,只要客户端连接,几秒钟后连接就会被丢弃。

这是正常的Python行为 - 如果客户端没有断开连接,连接是否应该保持打开状态?

这是我的剧本:

import socket
import sys

# Create a TCP/IP socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

# Bind the socket to the port
server_address = ('192.168.0.16', 3323)
print >>sys.stderr, 'starting up on %s port %s' % server_address
sock.bind(server_address) 

# Listen for incoming connections
sock.listen(1)

while True:
    # Wait for a connection
    print >>sys.stderr, 'waiting for a connection'
    connection, client_address = sock.accept()

    try:
        print >>sys.stderr, 'connection from', client_address

        # Receive the data in small chunks and retransmit it 
        while True:
            data = connection.recv(16)
            print >>sys.stderr, 'received "%s"' % data
            if data:
                print >>sys.stderr, 'sending data back to the client'
                connection.sendall(data)
            else:
                print >>sys.stderr, 'no more data from', client_address
                break

    finally:
        # Clean up the connection
        connection.close()

0 个答案:

没有答案