正确关闭插座

时间:2012-09-17 11:12:17

标签: python sockets

我正在尝试使用套接字建立服务器/客户端连接。但他们不能正常关闭,我无法理解为什么。

更新1

我已经纠正了我的愚蠢错误,而不是实际上在问题中调用s.close函数。 但结果证明这不是我的问题。

更新结束

这是我的服务器代码:

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import socket
import sys

if __name__ == '__main__':
    # Server connection
    s = socket.socket()          # Create a socket object
    host = socket.gethostname()  # Get local machine name
    port = 12345                 # Reserve a port for your service.

    print 'Server started!'
    print 'Waiting for clients...'

    s.bind((host, port))        # Bind to the port
    s.listen(5)                 # Now wait for client connection.
    c, addr = s.accept()     # Establish connection with client.
    print 'Got connection from', addr
    msg = c.recv(1024)

    print addr, ' >> ', msg

    if msg == 'close':
        print 'Closing down'
        c.send('SENT: Closing down')

    c.shutdown(socket.SHUT_RDWR)
    c.close()

这是我的客户代码:

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import socket

if __name__ == '__main__':
    # Server
    s = socket.socket()          # Create a socket object
    host = socket.gethostname()  # Get local machine name
    port = 12345                 # Reserve a port for your service.

    print 'Connecting to ', host, port
    s.connect((host, port))

    msg = raw_input('CLIENT >> ')
    s.send(msg)
    msg = s.recv(1024)
    print 'SERVER >> ', msg

    s.close()                     # Close the socket when done

这是它产生的错误信息:

In [13]: %run cjboxd.py
Server started!
Waiting for clients...
---------------------------------------------------------------------------
error                                     Traceback (most recent call last)
/usr/lib/python2.7/dist-packages/IPython/utils/py3compat.pyc in execfile(fname, *where)
    173             else:
    174                 filename = fname
--> 175             __builtin__.execfile(filename, *where)

/home/nine/slask/cjboxd.py in <module>()
     19     print 'Waiting for clients...'
     20 
---> 21     s.bind((host, port))        # Bind to the port
     22     s.listen(5)                 # Now wait for client connection.
     23     c, addr = s.accept()     # Establish connection with client.

/usr/lib/python2.7/socket.pyc in meth(name, self, *args)
    222 
    223 def meth(name,self,*args):
--> 224     return getattr(self._sock,name)(*args)
    225 
    226 for _m in _socketmethods:

error: [Errno 98] Address already in use

它将在一分钟后发挥作用。

2 个答案:

答案 0 :(得分:9)

您需要socket.socket.setsockopt,。i.e s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

虽然在进程结束时os将关闭套接字,但是显式调用close()是一个很好的行为。 但是,在此之后,本地地址(local_ip,local_port)在2 MSL(maximum segment lifetime)过去之前是不可用的。为什么?我们能做什么?你可以阅读这些:

http://www.tcpipguide.com/free/t_TCPConnectionTermination-3.htmhttp://www.unixguide.net/network/socketfaq/4.5.shtml

我很难发布比他们更明确的帖子:)。

答案 1 :(得分:3)

您正在呼叫s.close,而不是s.close()

如果希望客户端终止连接,则需要调用socket.close()方法。