我有一个由Java客户端和python服务器组成的程序。 python服务器可以接收多个连接,并且客户端将尝试每隔17秒连接到服务器。 我的问题: 服务器应该只接受与用户之前输入的IP的一个连接。
HOST = '0.0.0.0'
PORT = 1979
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print 'Socket created!'
try:
s.bind((HOST, PORT))
except socket.error as e:
print(e)
sys.exit()
print 'Socket bind complete'
s.settimeout(30)
s.listen(10)
print 'Listening...'
timeout = 8
timeout_start = time.time()
while time.time() < timeout_start + timeout:
try:
conn, addr = s.accept()
msg = conn.recv(1024)
print ('--------------------------------------')
print (msg)
except socket.timeout as e:
print(e,': No client out there :(')
s.close()
break
print 'Client connected: ' + addr[0] + ':' + str(addr[1])
print ('--------------------------------------')
s.close()
此套接字接受所有传入的连接。我想在套接字之前添加它:
connectip = raw_input('Please enter the IP of the client you want to connect to ')
,然后套接字应仅接受具有“ connectip”中指定的用户IP的客户端。
请原谅我的英语不好
答案 0 :(得分:1)
您仍然必须接受它,但是可以在传输任何数据之前将其关闭。
connectip = raw_input("Please enter the IP of the client you want to connect to ")
conn, addr = s.accept()
if addr[0] != connectip:
conn.shutdown(SHUT_RDWR)
conn.close()
else:
# do what ever you want here
顺便提一句,您真的应该切换到python 3,因为python 2将很快被弃用。