多线程服务器发送功能

时间:2016-02-05 15:05:20

标签: python multithreading tcp server

我有这个多线程服务器代码并且它可以工作但是当我输入要发送给客户端的东西时它不发送它只有在我发送数据字符串时发送功能才有效 谁知道问题是什么?

#!/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()

2 个答案:

答案 0 :(得分:0)

好吧,我至少可以看到一件事会阻止它按预期工作:

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

    clientsock.send("Welcome to the server ")

clientsock未定义。

答案 1 :(得分:0)

我的建议是不要尝试重新发明轮子(除非你想了解轮子是如何工作的)。已经有内置SocketServer同步,这意味着必须在下一个请求开始之前完成每个请求。

已经有非常容易使用的异步(非阻塞)TCP服务器的实现。如果你想要的东西不需要你学习框架而且只是开箱即用,我建议你simpleTCP。这是一个echo服务器的例子:

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!")