【问题标题】:Multi threaded server send function多线程服务器发送功能
【发布时间】:2016-05-15 14:46:32
【问题描述】:

我得到了这个多线程服务器代码,它可以工作,但是当我输入要发送给客户端的内容时,它不会发送它,发送函数只有在我发送数据字符串时才有效 有谁知道是什么问题?

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

【问题讨论】:

  • listen() 只需要调用一次。您可以通过bind() 将其上移。
  • 另外,你能解释一下“发送功能只有在我发送数据字符串时才有效”是什么意思吗?
  • 这意味着当我使用 self.csocket.send(data) 而不是 self.csocket.send(userInput) 它发送客户端发送的内容
  • 您是如何确定数据未发送的?尽可能精确。

标签: python multithreading tcp server


【解决方案1】:

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

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

    clientsock.send("Welcome to the server ")

clientsock 未定义。

【讨论】:

    【解决方案2】:

    我的建议是不要尝试重新发明轮子(除非您想了解轮子的工作原理)。已经有内置的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!")
    

    【讨论】:

      猜你喜欢
      • 2012-07-10
      • 1970-01-01
      • 2021-02-28
      • 1970-01-01
      • 2018-09-21
      • 2012-10-25
      • 1970-01-01
      • 2016-01-25
      • 1970-01-01
      相关资源
      最近更新 更多