Raj*_*Raj 2 python sockets multithreading client-server
我正在为我的大学项目做一个客户端 - 服务器项目,我们必须将登录分配给客户端.
客户端系统将每2秒请求其状态(以检查客户端是锁定还是解锁).和服务器将接受客户端请求并将客户端状态回复给系统.
但问题是服务器线程没有响应客户端请求.
客户线程:
def checkPort():
while True:
try:
s = socket.socket()
s.connect((host, port))
s.send('pc1') # send PC name to the server
status = s.recv(1024) # receive the status from the server
if status == "unlock":
disableIntrrupts() # enable all the functions of system
else:
enableInterrupts() # enable all the functions of system
time.sleep(5)
s.close()
except Exception:
pass
Run Code Online (Sandbox Code Playgroud)
服务器线程:
def check_port():
while True:
try:
print "hello loop is repeating"
conn, addr = s.accept()
data = conn.recv(1024)
if exit_on_click == 1:
break
if (any(sublist[0] == data for sublist in available_sys)):
print "locked"
conn.send("lock")
elif (any(sublist[0] == data for sublist in occupied_sys)):
conn.send("unlock")
print "unlocked"
else:
print "added to gui for first time"
available_sys.append([data,addr[0],nameText,usnText,branchText])
availSysList.insert('end',data)
except Exception:
pass
Run Code Online (Sandbox Code Playgroud)
但我的问题是服务器线程没有执行超过2次,所以它无法接受多次客户端请求.我们不能使用单服务器套接字处理多个客户端套接字?如何处理来自服务器的多个客户端请求?
谢谢你的帮助 !!
因为你的服务器会阻塞等待这一行的新连接
conn, addr = s.accept()
Run Code Online (Sandbox Code Playgroud)
这是因为调用喜欢.accept和.read是保持过程阻塞调用
您需要考虑替代设计,在哪里.
要实现第一个,看看multiprocessing,第二个是threading第三个稍微复杂一点,但是会产生最好的结果,在Python中用于事件驱动代码的库是扭曲的,但还有其他像
还有更多,我没有在这里列出.