yongyong-e

[Network] TCP multi-Thread 본문

프로그래밍/Python

[Network] TCP multi-Thread

Yonghan Kim 2017. 8. 12. 01:03

threading을 사용하여 여러 클라이언트와 연결이 가능하도록 구현


# Server

# serverTest4.py

import socket
from threading import Thread

HOST = socket.gethostname()
PORT = 50000
ADDR = (HOST, PORT)
BUFF_SIZE = 1024

class ClientThread(Thread):

def __init__(self,host,port,sock):
Thread.__init__(self)
self.host = host
self.port = port
self.sock = sock
print ("(Check the new thread) "+host+":"+str(port))

def run(self):
filename='iu.jpg'
f = open(filename,'rb')
while True:
l = f.read(BUFF_SIZE)
while (l):
self.sock.send(l)
#print('Sent ',repr(l))
l = f.read(BUFF_SIZE)
if not l:
f.close()
self.sock.close()
break

serverSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
serverSocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
serverSocket.bind(ADDR)
threads = []

while True:
serverSocket.listen(5)
print ("Waiting for connections...")
(clientSocket, (host, port)) = serverSocket.accept()
print ('Connection from ', (host, port))
newthread = ClientThread(host, port, clientSocket)
newthread.start()
threads.append(newthread)

for t in threads:
t.join()


# client

# clientTest4.py

import socket

HOST = socket.gethostname()
PORT = 50000
ADDR = (HOST, PORT)
BUFF_SIZE = 1024

clientSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
clientSocket.connect(ADDR)

with open('serverFile', 'wb') as f:
print ('file opened')
while True:
print('receiving data...')
data = clientSocket.recv(BUFF_SIZE)
print('(data)', data)
if not data:
f.close()
print ('file close')
break
f.write(data)

print('Successfully get the file')
clientSocket.close()
print('connection closed')


'프로그래밍 > Python' 카테고리의 다른 글

[Algorithm] 문자열의 문자들이 유일한가?  (0) 2017.09.01
[Algorithm] 문자열 뒤집기  (0) 2017.09.01
[Network] TCP file Transfer - 2  (0) 2017.08.11
[Network] TCP file Transfer - 1  (0) 2017.08.10
[Network] TCP simple example  (0) 2017.08.09
Comments