我正在使用python socket编写脚本。我想知道在python中关闭套接字的正确方法。我有两个脚本,它们既充当服务器又充当客户端,并且循环运行。我的脚本在下面
script1.py
import socket,time
port = 7785
def Socket_server():
global data
host = socket.gethostbyname(socket.gethostname())
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server.bind((host,port))
server.listen(1)
print("Listening")
c,addr = server.accept()
print("Got Connection from ",addr)
data = c.recv(1024)
print("Received Pool Id : %s" % data)
time.sleep(0.5)
server.shutdown(socket.SHUT_RDWR)
server.close()
def Socket_client():
master_ip = '127.0.0.1'
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
client.connect((master_ip,port))
print("Connected to master")
some_id = "send"
client.send(some_id)
print("sent data to master")
time.sleep(0.2)
client.shutdown(socket.SHUT_RDWR)
client.close()
Socket_server()
if data is not None:
# Do some work here
pass
Socket_client()
script2.py
import socket,time
port = 7785
def Socket_client():
master_ip = '127.0.0.0'
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
client.connect((master_ip,port))
print("Connected to master")
some_id = "send"
client.send(some_id)
print("sent data to master")
time.sleep(0.2)
client.shutdown(socket.SHUT_RDWR)
client.close()
def Socket_server():
global data
host = socket.gethostbyname(socket.gethostname())
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server.bind((host,port))
server.listen(1)
print("Listening")
c,addr = server.accept()
print("Got Connection from ",addr)
data = c.recv(1024)
print("Received Pool Id : %s" % data)
time.sleep(0.5)
server.shutdown(socket.SHUT_RDWR)
server.close()
Socket_client()
Socket_server() # wait for the script
我没遇到什么大问题,但是当我使用netstat -ano | findstr :7785
命令查看端口状态时,我得到了下面给出的侦听套接字的长列表
C:\Users\name>netstat -ano | findstr :7785
TCP 182.16.1.206:7785 0.0.0.0:0 LISTENING 4244
TCP 182.16.1.206:7785 0.0.0.0:0 LISTENING 4244
TCP 182.16.1.206:7785 0.0.0.0:0 LISTENING 4244
TCP 182.16.1.206:7785 0.0.0.0:0 LISTENING 4244
TCP 182.16.1.206:7785 0.0.0.0:0 LISTENING 4244
TCP 182.16.1.206:7785 0.0.0.0:0 LISTENING 4244
TCP 182.16.1.206:7785 0.0.0.0:0 LISTENING 4244
TCP 182.16.1.206:7785 0.0.0.0:0 LISTENING 4244
TCP 182.16.1.206:7785 0.0.0.0:0 LISTENING 4244
TCP 182.16.1.206:7785 0.0.0.0:0 LISTENING 4244
TCP 182.16.1.206:7785 0.0.0.0:0 LISTENING 4244
TCP 182.16.1.206:7785 0.0.0.0:0 LISTENING 4244
TCP 182.16.1.206:7785 0.0.0.0:0 LISTENING 4244
谁能告诉我为什么关闭套接字后我得到这个LISTENING
这个数字,这会影响我的程序吗?