大家好,我一直在尝试创建一个带有套接字的Python服务器,它永远阻塞在socket.accept处,忽略键盘中断并且不接受客户端连接,也许是一个SO问题,或者我的代码很糟糕(我在Windows上)
如果你想尝试这个,我可以向你发送文件,但这是代码
实用程序文件(线程类和常量的文件)
import threading
serveradd=("",8125)
class threadsocket(threading.Thread):
nsocketlock=threading.Lock()
nsocket=0
ntotalsocket=0
def __init__(self,socketclient,clientadd) -> None:
super().__init__()
self.socket=socketclient
self.add=clientadd
self.__class__.nsocketlock.acquire()
self.__class__.nsocket+=1
self.__class__.ntotalsocket+=1
self.__class__.nsocketlock.release()
@classmethod
def ntotalhost(cls):
return cls.ntotalsocket.encode('utf-8')
@classmethod
def nhost(cls):
return cls.nsocket.encode('utf-8')
def run(self) -> None:
while True:
print("adaslascana")
data=self.socket.recv(1024)
match data:
case "tt":
self.socket.send(threadsocket.ntotalhost())
case "ac":
self.socket.send(threadsocket.nhost())
case "ad":
self.socket.send(self.add.encode())
case "th":
self.socket.send((super().name()).encode())
case None:
self.__class__.nsocketlock.acquire()
self.__class__.nsocket-=1
self.__class__.nsocketlock.release()
self.socket.close()
break
服务器文件:
import socket
import Utilitypychat
socketserver=socket.socket()
socketserver.bind(Utilitypychat.serveradd)
socketserver.listen(5)
socketserver.settimeout(1.0)
print('partito')
try:
while True:
try:
socketclient, clientadd = socketserver.accept() #bloccante
Utilitypychat.threadsocket(socketclient,clientadd).start()
except socket.timeout:
pass
except KeyboardInterrupt:
print('finito')
finally:
socketserver.close()
客户文件
import socket
import Utilitypychat
client= socket.socket()
server_address = (Utilitypychat.serveradd)
client.connect(server_address)
try:
while True:
msg = input('msg to send (return to quit) --> ')
client.send(msg.encode())
data = client.recv(1024)
print(f'received: {data.decode()}')
except KeyboardInterrupt:
client.close()
我只是想让服务器回答一些想法(例如总共的连接数,现在有多少个,等等)以及可以连接并请求该数据的客户端,服务器只是在接受时阻塞并且不接受任何连接或键盘中断。
有几点需要注意。
在这行
Utilitypychat.py
中,您需要将接收到的数据解码为大小写匹配的字符串。否则永远不会匹配任何情况。 更改为
data=self.socket.recv(1024)
根据这就是为什么当你的
data = self.socket.recv(1024).decode("utf-8")
等待接收数据(
client.py
)时它会卡住,因为data = client.recv(1024)
永远不会发回任何东西(因为上面的server.py
问题)。在连接到服务器之前,请为客户端设置超时。Utilitypychat.py
# client.py
client.settimeout(5)
client.connect(server_address)
在您的
KeyboardInterrupt
中不起作用,因为它会阻塞。只有 timeouterror 或 socket.error 才会停止。在源代码中写着thisclient.py