나는 파이썬의 쓰레드 모듈을 사용하여 간단한 멀티 쓰레드 tcp 서버를 만들었다. 이 서버는 새로운 클라이언트가 연결될 때마다 새로운 스레드를 생성합니다.파이썬의 멀티 쓰레드 TCP 서버
#!/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("\nWelcome to the server\n\n")
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 "\nListening 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 변수가 덮어 쓰기되어 두 번째 연결의 소켓을 참조하기 때문에 이런 일이 발생하는지는 의문입니다. 나는 그것을 정정하고 어떻게 피하는가?
소켓 변수의 수가 제한되어 있고 각 연결마다 각 변수를 사용하는 배열을 사용하는 방법 외에 다른 방법이 있습니까? 여기의 나는이 좋은 클래스를 생성 한
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)
...
걱정하지 마세요. 좋은 질문입니다. StackOverflow에 오신 것을 환영합니다! – Jordan
마지막 두 줄에 도달하지 못하는 것 같습니다. 그게 의도적 인거야? –