smo*_*eSH 2 python sockets connection
我有一个由 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()
Run Code Online (Sandbox Code Playgroud)
该套接字接受所有传入连接。我想在套接字之前添加以下内容:
connectip = raw_input('Please enter the IP of the client you want to connect to ')
Run Code Online (Sandbox Code Playgroud)
然后套接字应该只接受具有用户在“connectip”中指定的IP的客户端。
请原谅我糟糕的英语
您仍然必须接受它,但可以在传输任何数据之前将其关闭。
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
Run Code Online (Sandbox Code Playgroud)
顺便说一句,您确实应该切换到 python 3,因为 python 2 很快就会被弃用。
归档时间: |
|
查看次数: |
2660 次 |
最近记录: |