我多次打开同一程序(准确地说是10次),而我都在尝试首先解决随机数。当他们解决了这个数字后,他们打开了一个服务器,所有其他相同程序正在等待连接的单独线程上监听;当他们最终连接时,我希望它们全部关闭。
import random
import os
import socket
import threading
import time
host = '192.168.1.139'
port = 8011
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
def verified():
print('Connection made successfuly')
time.sleep(10)
quit()
def network():
try:
s.connect(('192.168.1.135',8014))
f = s.recv(50)
finished = f.decode('utf-8')
if finished == 'completed':
quit()
except:
pass
def winner():
x = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
x.bind(('192.168.1.135', 8014))
x.listen(10)
con, address = x.accept()
con.send(bytes('completed', 'utf-8'))
def mine():
global guess
time.sleep(.000001)
guess = random.randint(0,1000)
print(guess)
tran = 500
while True:
mine()
if guess == 500:
print("Solved")
winner()
break;
else:
x = threading.Thread(target=network)
x.start()
由于某种原因,它正在连接到服务器,但没有退出程序,这可能是因为它正在连接到自身并快速退出吗?请帮忙,谢谢!
答案 0 :(得分:1)
实际上,我很困惑,但是很显然,当quit()
处于函数中时,它无法结束整个过程,因此,我建议您使用网络中的变量进行while循环将能够进行更改(甚至使用guess
):
guessing = True
while guessing:
mine()
if guess == 500:
print("Solved")
winner()
break;
else:
x = threading.Thread(target=network)
x.start()
并将网络更改为:
def network():
try:
s.connect(('192.168.1.135',8014))
f = s.recv(50)
finished = f.decode('utf-8')
if finished == 'completed':
#quit()
global guessing
guessing = False
except:
pass
我发现没有使用两个常量host
和port
def winner():
x = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
x.bind(('192.168.1.135', 8014))
x.listen(10)
connected = 0
while connected < 10:
con, address = x.accept()
con.send(bytes('completed', 'utf-8'))
connected += 1
是的,她正在交朋友
def winner():
x = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
x.settimeout(5) # WAITS FOR FIVE SECONDS
x.bind(('192.168.1.135', 8014))
x.listen()
while True:
try:
con, address = x.accept()
con.send(bytes('completed', 'utf-8'))
except socket.timeout: # IF IN FIVE SECONDS, RECEIVES NO CONNECTION
break
x.settimeout(5)
将使连接给出socket.timeout错误,如果超出设置的时间(在情况5中)而另一端没有任何响应。
现在我记得使用线程可以将客户端推送到另一个功能并“释放”客户端队列,但是我认为对于这种特殊情况,此解决方案更好