我尝试创建一个简单的客户端和一个使用线程的服务器。但有时我的服务器会输出错误:文件描述符错误。我在网上看到同样的问题和解决问题的解决方案。但最后,我没有成功解决我的问题。所以,如果您有任何想法如何解决问题,它将是优雅的。 谢谢!
我的代码:
import socket # Import socket module
from threading import Thread
# Global Variable
class ThreadServer:
def __init__(self, host, port):
try:
self.host = host
self.port = port
self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.sock.bind((self.host, self.port))
print "Server Start successfully !"
except Exception as e:
print "Something wrong %s" % (e)
def listen(self):
self.sock.listen(3) # Waiting for n client
while True:
client, address = self.sock.accept() # Establish connection with clients
client.settimeout(60)
Thread(target=self.listen_for_client, args=(client, address)).start()
def listen_for_client(self, client, address):
print "Got connection from", address
while True:
try:
msg = client.recv(1024)
if msg[0:4] == "USER":
user = msg[4:]
self.write_new_clients(address, user)
msg = 0
if msg:
print msg
client.send("Server : " + msg)
except Exception as e:
print "Something wrong %s" % (e)
client.close()
def write_new_clients(self, address, user):
my_file = open("Clients_list.txt", "a+")
line = my_file.readline()
for i in line:
if str(address) in line:
print "Already Exist !"
else:
my_file.write(str(user) +"::" + str(address) + "\n")
def main():
ThreadServer("0.0.0.0", 8350).listen()
if __name__ == "__main__":
main()