2016-02-05 78 views
0

我得到這個多線程服務器代碼和它的作品,但是當我輸入的東西發送給客戶端的不發送,如果我發送的數據串 任何人都知道出了什麼問題發送功能才起作用?多線程服務器發送功能

#!/usr/bin/env python 

import socket, threading 

class ClientThread(threading.Thread): 

    def __init__(self, ip, port, clientsocket): 
     threading.Thread.__init__(self) 
     self.ip = ip 
     self.port = port 
     self.csocket = clientsocket 
     print "[+] New thread started for "+ip+":"+str(port) 

    def run(self):  
     print "Connection from : "+ip+":"+str(port) 

     clientsock.send("Welcome to the server ") 

     data = "dummydata" 

     while len(data): 
      data = self.csocket.recv(2048) 
      print "Client(%s:%s) sent : %s"%(self.ip, str(self.port), data) 

      userInput = raw_input(">") 
      self.csocket.send(userInput) 

     print "Client at "+self.ip+" disconnected..." 

host = "0.0.0.0" 
port = 4444 

tcpsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 
tcpsock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) 

tcpsock.bind((host, port)) 

while True: 
    tcpsock.listen(4) 
    print "nListening for incoming connections..." 
    (clientsock, (ip, port)) = tcpsock.accept() 

    #pass clientsock to the ClientThread thread object being created 
    newthread = ClientThread(ip, port, clientsock) 
    newthread.start() 
+0

'聽()'只需要調用一次。你可以通過'bind()'來移動它。 – glibdud

+0

另外,你能解釋一下「發送函數只在發送數據串時才起作用」的意思嗎? – glibdud

+0

這意味着當我使用self.csocket.send(數據)而不是self.csocket.send(userInput)時,它發送客戶端發送的內容 –

回答

0

好吧,我可以看到至少有一點是可以防止這種按預期工作:

def run(self):  
    print "Connection from : "+ip+":"+str(port) 

    clientsock.send("Welcome to the server ") 

clientsock是不確定的。

+0

我刪除了它,但仍然不能正常工作 –

0

我的建議是不要試圖重新發明輪子(除非你想了解如何車輪作品)。已經有內置的SocketServer,但是這是同步,這意味着每個請求必須完成才能開始下一個請求。

已經有非常容易使用的異步(非阻塞)TCP服務器的實現。如果你想要的東西不需要你學習一個框架,只需要開箱即用,我建議simpleTCP。下面是一個回聲服務器的例子:

from simpletcp.tcpserver import TCPServer 

def echo(ip, queue, data): 
    queue.put(data) 

server = TCPServer("localhost", 5000, echo) 
server.run() 

而這裏的連接到它的客戶機的一個例子:

from simpletcp.clientsocket import ClientSocket 

s1 = ClientSocket("localhost", 5000) 
response = s1.send("Hello, World!")