Python 中的多线程 TCP 服务器 [英] Multi Threaded TCP server in Python

查看:58
本文介绍了Python 中的多线程 TCP 服务器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 python 的 threding 模块创建了一个简单的多线程 tcp 服务器.每次连接新客户端时,此服务器都会创建一个新线程.

I have created a simple multi threaded tcp server using python's threding module. This server creates a new thread each time a new client is connected.

#!/usr/bin/env python

import socket, threading

class ClientThread(threading.Thread):

    def __init__(self,ip,port):
        threading.Thread.__init__(self)
        self.ip = ip
        self.port = port
        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 = clientsock.recv(2048)
            print "Client sent : "+data
            clientsock.send("You sent me : "+data)

        print "Client disconnected..."

host = "0.0.0.0"
port = 9999

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

tcpsock.bind((host,port))
threads = []


while True:
    tcpsock.listen(4)
    print "
Listening for incoming connections..."
    (clientsock, (ip, port)) = tcpsock.accept()
    newthread = ClientThread(ip, port)
    newthread.start()
    threads.append(newthread)

for t in threads:
    t.join()

然后我打开了两个新终端并使用netcat连接到服务器.然后,当我使用我连接的第一个终端输入我的第一个数据并将其发送到服务器时,来自服务器的回复到达另一个终端并且第一个连接断开.我猜到了原因,但我怀疑这是否会发生,因为 clientsock 变量被覆盖,因此它指的是第二个连接的套接字.我是否正确,然后如何避免这种情况?

Then I opened two new terminals and connected to the server using netcat. Then, when I type and send my first data to the server using the first terminal I connected, reply from the server comes to the other terminal and first connection got disconnected. I guessed the reason but I am doubtful whether this happens because clientsock variable is overwritten so that it refers to the second connection's socket. Am I correct and then how to avoid that?

除了使用套接字变量数量有限的数组并为每个连接使用每个变量之外,还有其他方法吗?

Is there a way other than using an array with limited number of socket variables and using each variable for each connection?

推荐答案

您应该像处理 IP 地址和端口一样将客户端 sock 传递给线程:

You should pass the client sock to the thread like you do with the ip address and the port:

class ClientThread(threading.Thread):

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

    def run(self):
        # use self.socket to send/receive

...
(clientsock, (ip, port)) = tcpsock.accept()
newthread = ClientThread(ip, port, clientsock)
...

这篇关于Python 中的多线程 TCP 服务器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆