yongyong-e
[Network] TCP file Transfer - 1 본문
client에서 server로 접속 시 파일전송 구현
# Server
# serverTest2.py
from socket import *
import struct
HOST = '192.168.0.10'
PORT = 50000
ADDR = (HOST, PORT)
BUFF_SIZE = 1024
FILE_NAME = 'clientFile.jpg'
FILE_LEN = 0
serverSocket = socket(AF_INET, SOCK_STREAM)
serverSocket.bind(ADDR)
serverSocket.listen(5)
clientSocket, addr = serverSocket.accept()
FILE_SIZE = clientSocket.recv(8)
FILE_SIZE = struct.unpack('L', FILE_SIZE)[0]
f = open(FILE_NAME, 'wb')
while True:
client_file = clientSocket.recv(BUFF_SIZE)
# print(client_file)
if not client_file:
break
f.write(client_file)
FILE_LEN += len(client_file)
if FILE_LEN == int(FILE_SIZE):
break
f.close()
print('client : ' + FILE_NAME + ' file transfer')
server_msg = FILE_NAME + ' received complete'
# server_msg = bytes(server_msg, encoding='utf-8')
# clientSocket.send(server_msg)
clientSocket.send(server_msg.encode())
clientSocket.close()
# Client
# clientTest2.py
from socket import *
import os
import sys
import struct
HOST = '192.168.0.10'
PORT = 50000
ADDR = (HOST, PORT)
BUFF_SIZE = 1024
FILE_NAME = 'iu.jpg'
clientSocket = socket(AF_INET, SOCK_STREAM)
clientSocket.connect(ADDR)
FILE_SIZE = os.path.getsize(FILE_NAME)
FILE_SIZE = struct.pack('L', FILE_SIZE)
while True:
try:
f = open(FILE_NAME, 'rb')
I = f.read(BUFF_SIZE)
clientSocket.send(FILE_SIZE)
while I:
clientSocket.send(I)
I = f.read(BUFF_SIZE)
f.close()
print('(check) ' + FILE_NAME + ' transfer complete')
server_msg = clientSocket.recv(BUFF_SIZE)
print('server : ' + server_msg.decode())
clientSocket.close()
sys.exit()
except Exception as e:
sys.exit()
'프로그래밍 > Python' 카테고리의 다른 글
[Algorithm] 문자열 뒤집기 (0) | 2017.09.01 |
---|---|
[Network] TCP multi-Thread (3) | 2017.08.12 |
[Network] TCP file Transfer - 2 (0) | 2017.08.11 |
[Network] TCP simple example (0) | 2017.08.09 |
[Ubuntu16.04] PyCharm Python IDE 설치 (0) | 2017.08.08 |