我正在使用套接字和多線程進行基本的聊天程序。該程序連接,並在從客戶端發送的消息,執行時會提高在服務器端這個錯誤:使用多線程的基本Socket聊天程序引發錯誤
Exception in thread Thread-1:
Traceback (most recent call last):
File "C:\Python27\lib\threading.py", line 810, in __bootstrap_inner
self.run()
File "C:\Python27\lib\threading.py", line 763, in run
self.__target(*self.__args, **self.__kwargs)
File "C:\Users\jclarke14\Desktop\Server - 2.py", line 25, in check_for_data
data = c.recv(1024)
File "C:\Python27\lib\socket.py", line 174, in _dummy
raise error(EBADF, 'Bad file descriptor')
error: [Errno 9] Bad file descriptor
我是一個初學者,新多線程和插座。我究竟做錯了什麼?
這裏是我的客戶端代碼:
#Check For Incoming Data
def check_for_data():
while True:
data = s.recv(1024)
print "Other: " + data
print
#Send Data
def send_data():
while True:
message = raw_input("You: ")
print
s.sendall(message)
#Start Threads
t = threading.Thread(target=send_data)
t.daemon = True
t.start() #1
t = threading.Thread(target=check_for_data)
t.daemon = True
t.start() #2
和代碼服務器:
c, addr = s.accept()
print "Connection From: " + str(addr)
print
def check_for_data():
while True:
data = c.recv(1024)
print "Other: " + str(data)
print
def send_data():
while True:
message = raw_input("You: ")
print
c.sendall(message)
#Start Threads
t = threading.Thread(target=send_data)
t.daemon = True
t.start() #1
t = threading.Thread(target=check_for_data)
t.daemon = True
t.start() #2
完整的代碼可以在這裏找到:https://drive.google.com/folderview?id=0B3t3mUQs3K-iLWY3Y3JZX2YzU2c&usp=sharing
謝謝:)
謝謝您的回答。我在哪裏關閉套接字? –
我是一個初學者:( –
@ J.Clarke:文件的最後一行:'c.close()'。這會關閉連接到客戶端的套接字 – mhawke