프로그램 진행 순서
1. 서버를 실행
2. 클라이언트를 실행
3. 클라이언트에서 다운받을 파일의 이름을 지정함(형식을 지정하지 않음 -> .jpg로 저장)
4. 서버에서 보낼 파일을 선택함(형식을 지정함)
5. 클라이언트에서 파일 수신 후 연결 종료
6. 서버는 그대로 유지
#모듈을 참고하면서 가져온 주석은 그대로 나뒀음
server.py
import socket # Import socket module
port = 60000 # Reserve a port for your service.
s = socket.socket() # Create a socket object
host = socket.gethostname() # Get local machine name
s.bind((host, port)) # Bind to the port
s.listen(5) # Now wait for client connection.
## code 0 -> no touch
## code 1 -> server recv
## code 2 -> you handle
print '[-]Server listening....'
while True:
conn, addr = s.accept() # Establish connection with client.
print '[-]Got connection from : ', addr
data = conn.recv(1024)
rev_data = repr(data)
print('[1]Server received : ' + rev_data) # 여기서 rev_data가 따움표를 그대로 포함하였고 딱히 제거할 필요를 못느꼈음.
if rev_data[1:4] == "0gf" :
print('[-]File transfer request option!')
filename ='source\\'+ raw_input('[2]Choose image file to transfer(format needed) : ') # choose image file
f = open(filename,'rb') # file open with option 'rb' rb옵션은 바이너리 파일을 읽어서 1바이트씩 읽는 옵션
l = f.read(1024)
while (l):
conn.send(l)
l = f.read(1024)
f.close()
print('[-]Done sending----------------------------------')
##conn.send('Thank you for connecting')
conn.close()
client.py
import socket # Import socket module
import time # for using sleep method
s = socket.socket() # Create a socket object
host = socket.gethostname() # Get local machine name
port = 60000 # Reserve a port for your service.
s.connect((host, port))
print('[-]You are ready to get the file')
file_name = raw_input('[2]File name(not format) : ')
s.send("0gf")
with open(file_name+'.jpg', 'wb') as f:
print '[-]File opened'
while True:
data = s.recv(1024)
if not data :
break
# write data to a file
if data != '' :
f.write(data)
f.close()
print('[-]Successfully get the file')
s.close()
print('[-]connection closed')
while True :
time.sleep(10)
'Python > 학습' 카테고리의 다른 글
Image transfer program through socket server 3 (0) | 2017.01.23 |
---|---|
Image transfer program through socket server 2 (0) | 2017.01.22 |
ghost gets coins (0) | 2016.07.31 |
remove black blocks with mouse(sprite) (0) | 2016.07.28 |
moving circle every 2 secs (using class) (0) | 2016.07.28 |
댓글