자바~하둡
python) Thread pickle socket
히드라✧
2022. 2. 24. 18:40
Thread¶
- 한 Process 안에서 동시에 실행되는 소규모 Process
- 동시에 2개의 함수를 실행할 수 있도록 지원하는 API
- 병행처리 가능 (네트웍으로 송신과 동시에 수신도 가능함)
- 웹서버에서는 동시에 접속하는 클라이언트마다 쓰레드를 생성하여 병행처리 (<->순차처리)
- ### Java의 Thread 생성법
- 가상의 CPU(VCPU): Thread, 코드를 실행하는 디바이스
- Thead : 코드(Runnable)를 실행할 수 있다
- run명령으로 실행한다.
- 코드실행 조건: Runnable 인터페이스를 implements해야 한다.
- Thread t = new Thread( new Runnable(){...});
- t.start(); //start 하면 run 메소드 실행
- import theading.Thread
- t = theading.Thread(target=함수 이름, args=('a','b'))
- t.start()
- # python
In [ ]:
import threading # 모듈 이름 = 파일이름
import time
import datetime
# 초시계만들기
def t1(name): # 쓰레드가 실행할 함수
while True: # 무한 루프
print(name, datetime.datetime.now())
time.sleep(1) # 1초 쉼
In [ ]:
t1("현재 시간")
In [ ]:
t1 = threading.Thread(target=t1, args=("현재시간",)) # args 는 튜플 자료형으로 준다
t1.start()
In [ ]:
import threading
import time
class CommIO:
def inMethod(self,msg): # 쓰레드가 실행할 메소드
while True:
print("in")
time.sleep(1)
def outMethod(self):
while True:
print("out")
time.sleep(1)
In [ ]:
obj=CommIO() #자바에서 인스턴스
In [ ]:
t2 = threading.Thread(target=obj.inMethod,args=("메세지",))
In [ ]:
t2.start()
Java¶
class MyTheard extends Thread { public void run(){ //VCPU가 실행할 코드 } }
MyThread t = new MyThread() t.start()
In [ ]:
import threading
import time
import datetime
class MyGame(threading.Thread): # 쓰레드를 상속 시킴
def __init__(self,name): # 가상 CPU
threading.Thread.__init__(self)
print(name, 'instanciated')
self.daemon = True # 부모쓰레드를 종료하면 자식쓰레드가 종료되게 함
def run(self): # 작동코드
while True:
print(datetime.datetime.now())
rime.sleep(1)
# 쓰레드를 stop 시키는 것이 아니라 이 루프를 나오게 하여 종료 시킨다. break or while False:
t1_thread = MyGame('game thread')
t1_thread.start()
In [ ]:
import time
import datetime
def test_loop():
n=0
while True:
n+=1
print('숫자', n)
time.sleep(1)
import threading
run = threading.Thread(target=test_loop)
run.start()
def some_logic():
n=0
while True:
n-=1
print('음수',n)
time.sleep(1)
run2=threading.Thread(target=some_logic)
run2.start()
while True:
print("날짜",datetime.datetime.now())
time.sleep(1)
Pickle을 사용한 객체 직렬화(Serialization)¶
In [ ]:
import pickle
my_list=[3,4,5,6,7]
with open('/Users/lucas/test/data.pickle','wb')as fw:
pickle.dump(my_list,fw) # 파일에 저장
print('리스트객체 길렬화 성공')
In [ ]:
# 역직렬화 (직렬화된 데이터를 다시 원래의 객체로 복원)
with open('/Users/lucas/test/data.pickle','rb')as fr:
data=pickle.load(fr) # 파일에서 읽어와서 역질렬화
print(type(data)) # 리스트로 바로 나옴
data[0]
In [ ]:
# serObj = pickle.dumps(obj) #데이터를 다른 곳으로 보낼수 있다.
# Obj2 = pickle.loads(serObj)
In [ ]:
# Product 객체를 직렬화 하여 파일에 저장하고 다시 로드하여 객체의 속성을 화면에 표시해보세요
In [ ]:
class Product:
def __init__(self,num,pname,price,company,date):
self.num=num
self.pname=pname
self.price=price
self.company=company
self.date=date
def __str__(self):
return f'{self.num}\t{self.pname}\t{self.price}\t{self.company}\t{self.date}'
In [ ]:
product1=Product(1,"football",150,"wilson","2022-02-25")
product2=Product(2,"headgear",360,"riddell","2022-02-25")
product3=Product(3,"cleat",300,"nike","2021-02-25")
productList=[]
productList.append(product1)
productList.append(product2)
productList.append(product3)
import pickle
with open('/Users/lucas/test/product.pickle','wb')as fw:
pickle.dump(productList,fw)
print("겍체 직렬화 저장 성공")
In [ ]:
with open ('/Users/lucas/test/product.pickle','rb')as fr:
data=pickle.load(fr)
print(type(data))
print(data)
for prod in data:
print(prod)
In [ ]:
# 객테 직렬화하여 메모리에 저장하는 예
# serObj = pickle.dumps(obj) #데이터를 다른 곳으로 보낼수 있다.
# Obj2 = pickle.loads(serObj)
In [ ]:
p=Product(1,"football",150,"wilson","2022-02-25")
In [ ]:
pSerObj = pickle.dumps(p)
In [ ]:
p2=pickle.loads(pSerObj)
In [ ]:
print(p2.pname)
In [ ]:
print(p2)
In [ ]:
# pickle과 파일을 이용한 CRUD
# 키보드에서 Student 정보 (id, name, year, email)를 입력 바고
# 파일에 저장하여 관리하는 기능 작성
# 파일에 저장할 때는 pickle 직렬화 이용
# 리스트에 Student를 다수개 저장하고 리스트를 직렬화하여 파일에 저장
# 추가, 수정, 삭제 할떄는 메모리에서 싪행 후 직렬화하여ㅛ 파일에저장
# 목록(s), 검색, 추가(a), 수정(u), 삭제(d), 종료(x)
In [ ]:
import pickle
class Student:
def __init__(self,id,name=0,year=0,email=0):
self.id=id
self.name=name
self.year=year
self.email=email
def __eq__(self,other):
return self.id==other.id
def __str__(self):
return f'{self.id} {self.name} {self.year} {self.email}'
def getStr(self):
return f'{self.id} {self.name} {self.year} {self.email}'
In [ ]:
studentList=[]
In [ ]:
def load():
with open('/Users/lucas/test/student.pickle','rb')as fr:
return pickle.load(fr)
In [ ]:
def save(saveList):
with open('/Users/lucas/test/student.pickle','wb')as fw:
pickle.dump(saveList,fw)
print('학생정보 반영성공')
In [ ]:
def add():
studentList=load()
kbd=input("id: name: year: email:")
[id,name,year,email]=kbd.split()
inputSt=Student(id,name,year,email)
studentList.append(inputSt)
save(studentList)
In [ ]:
def show():
loadList=load()
for student in loadList:
print(student)
In [ ]:
def find():
kbd=input("찾으실 학생 id 입력:")
finding=Student(kbd)
studentList=load()
for student in studentList:
if student.__eq__(finding):
print(student)
In [ ]:
def update():
kbd=input("수정하실 학생 id 입력:")
finding=Student(kbd)
studentList=load()
for student in studentList:
if student.__eq__(finding):
print(student)
cmd=input("위 학생정보를 수정할까요? (y)")
if cmd=='y':
print("새로운 이메일을 입력하세요")
newEmail=input("이메일:")
student.email=newEmail
save(studentList)
In [ ]:
def delete():
kbd=input("삭제하실 학생 id 입력:")
finding=Student(kbd)
studentList=load()
idx=0
for student in studentList:
if student.__eq__(finding):
print(student)
idx=studentList.index(student)
studentList.remove(studentList[idx])
cmd=input("위 학생정보를 삭제할까요? (y)")
if cmd=="y":
save(studentList)
In [ ]:
while True:
cmd=input("# 목록(s), 검색(f), 추가(a), 수정(u), 삭제(d), 종료(x)")
if cmd=='x':
break
elif cmd=='s':
show()
elif cmd=='a':
add()
elif cmd=='f':
find()
elif cmd=='u':
update()
elif cmd=='d':
delete()
print("프로그램 종료")
In [ ]:
class Student2:
def __init__(self,id,name=None,year=0,email=None):
self.id=id
self.name=name
self.year=year
self.email=email
def __str__(self):
return f'{self.id} {self.name} {self.year} {self.email}'
def __eq__(self,other):
return self.id==other.id
In [ ]:
studentList2=[]
fname='/Users/lucas/test/studentList.txt'
In [ ]:
def print_list(sList):
for s in sList:
print(s)
In [ ]:
def get_list():
try:
with open(fname,'rb') as fr:
sList=pickle.load(fr)
return sList
except:
with open(fname,'wb')as fw:
return []
In [ ]:
def find2():
sid = input("아이디:")
sList=get_list()
idx=sList.index(Student2(sid))
print(sList[idx])
In [ ]:
def add2():
sIn=input('아이디 이름 학년 이메일:')
[id,name,year,email]=sIn.split()
s=Student2(id,name,year,email)
sList=get_list()
sList.append(s)
save_list(sList)
print('파일에 저장')
In [ ]:
import pickle
def save_list(sList):
with open(fname,'wb')as fw:
pickle.dump(sList, fw)
In [ ]:
def update2():
sid = input('수정대상 아이디:')
s=Student2(sid)
sList=get_list()
idx=sList.index(s)
sYearEmail=input('새 학년 새 이메일:')
[year,email]=sYearEmail.split()
sList[idx].year=year
sList[idx].email=email
save_list(sList)
print('수정성공')
In [ ]:
def delete2():
sid=input('삭제대상 아이디')
s=Student2(sid)
sList=get_list()
try:
idx=sList.index(s) #
except:
print('삭제 대상 정보가 없습니다')
return
sList.remove(s)
save_list(sList)
print('삭제성공')
In [ ]:
while True:
menu=input('목록(s),검색(f),추가(a),수정(u),삭제(d),종료(x)')
if menu=='s':
print_list(get_list())
elif menu=='f':
find2()
elif menu=='a':
add2()
elif menu=='u':
update2()
elif menu=='d':
delete2()
elif menu=='x':
break
else:
print('메뉴입력 오류')
print("프로그램 종료")
TCP_Socket _ Server
In [1]:
class MsgObj:
def __init__(self,num,msg):
self.num=num
self.msg=msg
def __str__(self):
return f'{self.num}\t{self.msg}'
In [2]:
from socket import * #socket.xxx
import time
import pickle
serverSock=socket(AF_INET,SOCK_STREAM)
serverSock.bind(('',1122)) # 1024 이후의 포트번호 이전은 많은 서버들이 이미 사용중
serverSock.listen()
print('서버 작동...') #실헹하면 보안경고창 표시됨, 액세스 허용
clientSock, addr = serverSock.accept() #튜플 리턴 (clentSock,addre)생략
print(str(addr),'클라이언트 접속됨')
msg = '서버에 접속 성공'
clientSock.send(msg.encode('utf-8')) #바이트 단위로 전송됨(문자열 이외도 가능)
#클라이언트가 접속해야 실행된다
# 직렬화된 오브젝트 수신
obj_bytes=clientSock.recv(1024*10)
msgObj = pickle.loads(obj_bytes)
print('서버에 전달된 오브젝트',msgObj)
time.sleep(1) #기다림 없이 서버가 끝나버려서 수신이 안될수 있다.
print('서버 종료')
TCP_Socket _ Client
In [1]:
class MsgObj:
def __init__(self,num,msg):
self.num=num
self.msg=msg
def __str__(self):
return f'{self.num}\t{self.msg}'
In [2]:
#Client
from socket import *
import pickle
import time
clientSock=socket(AF_INET, SOCK_STREAM)
clientSock.connect(('127.0.0.1',1122))
msg = clientSock.recv(1024) # 한번에 가져올 바이트 수 (부족하면 반복호출해야 함)
print(msg.decode('utf-8'))
mobj=MsgObj(11,'잘 가야 할텐데.....')
obj_bytes = pickle.dumps(mobj)
clientSock.send(obj_bytes)
time.sleep(1)
print('클라이언트 종료')