我正在尝试使用套接字建立服务器/客户端连接。但是它们不会正确关闭,我无法理解为什么。
更新 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
它会在一分钟后工作。