WebSocket - 예엣날에 공부했던 내용 정리

# Websocket WebSocket Tutorial with Python 웹소켓이란, HTTP 프로토콜의 단점을 극복하고 실시간 full duplex통신을 위한 기술이다. 개인적으로 웹소켓의 핵심은 Real-time dataflow라 생각한다. 1. 웹소켓이 맺어지는 흐름 Client가 TCP/IP 요청을 보내면 서버에서 TCP/IP 요청을 수락한다. 그 후 Client는 서버에게 웹소켓 handshake를 요청하고 서버는 이를 수락한다. 이렇게 하면 http에서 websocket으로 프로토콜이 전환되며 connection이 만들어지고  이 때부터 웹소켓을 통해 데이터를 송, 수신한다. * 웹소켓은 Http와 전혀 다르다. 다만 웹소켓을 만드는데에 http가 개입을 하는 것이다. 웹소켓이 만들어지면 서버는 응답코드 101을 보낸다. (101은 프로토콜이 전환되었음을 알리는 응답코드다) 2. 웹소켓은 왜 쓰는 것인가? Http보다 더 나은 점이 있을테니 websocket을 쓸텐데 그 점은 무엇일까? 그걸 알기 위해서는 일단 비동기 http 통신방식인 Ajax(XMLHttpRequest, 이하 htttp)에 대해 좀 알아야 한다. AJAX의 본래 이름은 XMLhttprequest이다. 이 기술이 나오고 비동기 통신이 팍! 떡상했다. 하지만 http엔 단점이 있다. 크로스 오리진 문제와 헤더의 용량 문제다. 3. 웹소켓이 http보다 더 나은 점은? 웹소켓과 비교하면 http통신은 항상 요청헤더가 부여되기 때문에 1바이트의 정보를 송신하고 싶어도 수킬로바이트에 달하는 쓸모없는 정보를 보내야한다. "에이 1바이트를 보낼 일이 언제 있다고" 하는 생각이 먼저 들었는데, 생각해보면 채팅같은 경우엔 말을 짧게 짧게 보내기도 한다.  "ok" 보내면 겨우 2바이트다. 이걸 매번 http로 통신한다면 저 짧은 두 글자를 보내는데도 많은 트래픽이 소요될 것이고 이는 성능의 문제로 귀결될 것이다. Real-time application에서는...

생산수단은 반드시 필요하다

자본주의에서 부유 계층에 속하는지 아닌지 는 결국 생산수단을 소유하는가에 달려있다. 생산수단이 만들어내는 생산물을 받는 입장일지라도 양이 크다면 일시적으로 부유해질 수 있지만 최대 본인 세대까지 넉넉하게 살 수 있을 듯하다. 일시적 부가 아닌 부유 계층에 속하기 위해서는 생산수단을 소유하는 것이 중요하다. 일생을 살며, pay라는 동사가 능동태가 아닌 수동태로만 쓰여진다면 나와 내 후세대는 절대로 돈에서 자유로워 질 수 없을 것이다. 삶은 많은 경험과 도전과제들이 있다. 돈 때문에 이런 것들을 포기해야 한다면 안타까울 것이다. 그래서 부유한 삶 그 자체가 목표가 아니고 부유하기 때문에 다양한 것을 시도하고 실패할 수 있는 삶을 추구한다.  먹고사니즘에 얽매여 내 삶의 범위를, 자유를 한정짓지 않도록 언젠가 반드시 생산수단은 소유해야한다. 개발자라는 직업은 다른 직업보다 수월하게 본인의 지식과 실력을 생산수단으로 만들 수 있다. 완전한 생산수단이라기 보다는 반(半) 생산수단이라고 보는 것이 합당할 것 같다. 좀 더 발전하여 내 스스로가 완전한 반(半) 생산수단이 되고 나아가 생산수단을 소유할 수 있는 삶을 살 수 있기를.

2020.04.27 TIL 스프링 - Spring Form Tag 사용하기

Spring의 form 태그는 이렇게 prefix를 붙이고 modelAttribute를 추가하여 사용한다. <form:form modelAttribute="student">   <form:input path="name">    // 자동으로 student모델의 getName()의 값이 초기 값으로 세팅되고, 이후에 submit을 하면 setName()이 호출된다. 언제나 case 유의할 것! 처음에 모델을 포함해서 HTML을 렌더링 해주는 controller는 아래와 같이 사용한다. ``` @RequestMapping("/showForm") public String showForm(Model theModel) { Student theStudent = new Student(); theModel.addAttribute("student", theStudent); theModel.addAttribute("theCountryOptions", countryOptions); return "student-form"; } ``` HTML 코드는 이러하고 ``` <form:form action="processForm" modelAttribute="student"> Student first name: <form:input path="firstName"/><br> Student last name: <form:input path="lastName"/><br> <form:select path="country"> <form:options items="${theCountryOptions}"/> </for...

2020.04.25 TIL 스프링 - XML 없이 Configuration 하기

## Configuration 클래스 작성 1. Create java class with @Configuration, @ComponentScan annotation @Configuration @ComponentScan(PACKAGE_NAME) public class MyConfig {} 2. Load Config class context at main file. main { AnnotationConfigApplicationContext context =   new AnnotationConfigApplicationContext(MyConfig.class); } ## Bean도 SpringContainer Config안에서 만들기 1. Config Class에서 @Bean annotation으로 바로 Bean을 주입할 수 있다. - 사전에 필요한 사항은 Bean 클래스가 구현할 인터페이스, Bean 클래스이다. @Configuration public class MyConfig() {   @Bean   public Something something() {     // 이 때 MySomething이 Bean으로 동작할 클래스로, Something을 구현하고 존재하고 있어야 함.     return new MySomething();   }   @Bean   public Another another() {     // 이 때 MyAnother Bean은 something을 inject 받는 Bean이다.     return new MyAnother(something());  //   } } ## Full Code ``` Main public class SwimJavaConfigDemoApp { public static void main(Stri...

2020.04.24 TIL 스프링 - Bean Scope Detail with Annotation

Bean은 특별한 지정 값이 없으면 언제나 싱글톤으로 만들어진다. https://everupgrade.blogspot.com/2020/04/20200408-bean-lifecycle-annotation-bean.html 그런데 이 설정을 굳이 xml이 아닌 Bean Class에서 편하게 할 수 있다. ``` @Component @Scope( singleton(default) or prototype(매번 새로운 객체 생성) or global(용어는 확실치않음. flask g처럼 동작 등 ) public class Bean... (대충 bean 클래스) ``` init, destroy hook도 마찬가지이다. ``` @Component public class Bean... (대충 bean 클래스)     @PostConstruct   public String initMethod() {..대충 bean 함수}   @PreDestroy   public String destroyMethod() {..대충 bean 함수} ``` 주의사항 prototype은 PreDestroy Annotation이 동작하지 않는다. 다른 Scope들은 모두 관리가 되는데 prototype은 스프링 컨테이너가 생성까지만 관여하고 destroy는 관여하지 않는다. 만약 prototype bean에 destroy 훅을 달고 싶으면 Bean이 DisposableBean interface를 구현하고 해당 인터페이스가 제공하는 destroy() 함수를 구현해야한다고 한다. 참고소스:   destroy-protoscope-bean-with-custom-processor.zip

2020.04.22 TIL 스프링 - AutoWiring(2), Qualifier

Bean Inject하는 방법은 3가지가 있고 아래와 같다. 1. Constructor Injection @Component public class NewCoach implements Coach {         private FortuneService fs;     @Autowired public NewCoach(@Qualifier("sadFortuneService") FortuneService fortuneService) {}; @Override public String getDailyWorkout() { // TODO Auto-generated method stub return null; } 2. Setter Injection @Component public class NewCoach implements Coach {         private FortuneService fs; @Autowired public String setFortuneService(FortuneService fs) {                 this.fs = fs; } 3. Field Injection @Component public class NewCoach implements Coach {         @Autowired         @Qualifier("happyFortuneService")         private FortuneService fs; Private 필드에 @Autowired를 붙여서 자동으로 Bean을 주입하고 사용하는 방식은 혼자 자바, 스프링 공부하는 내내 사용했던 문법인데 ...

2020.04.15 파이썬 - Shelve

파이썬 Built-in에 이런 모듈이 있는것을 처음 알았다. import shelve class CustomClass: def __init__ ( self , value): self .value = value def __repr__ ( self ): return f'<class: { self .__class__. __name__ } >' with shelve.open( 'test.db' ) as f: f[ 'my_int' ] = 100 f[ 'my_float' ] = 100.555 f[ 'my_str' ] = 'hello world!' f[ 'my_dict' ] = dict ( hello = 'world' ) f[ 'my_custom_class' ] = CustomClass( 'MyCustomClass' ) with shelve.open( 'test.db' ) as f: print (f[ 'my_int' ]) print (f[ 'my_float' ]) print (f[ 'my_str' ]) print (f[ 'my_dict' ]) print (f[ 'my_custom_class' ]) print (f[ 'my_custom_class' ].value) $ 100 $ 100.555 $ hello world! $ {'hello': 'world'} $ <class: CustomClass> $ MyCustomClass 이렇게 파이썬 객체들 중 picklable 한 객체들은 모두 파일에 저장해둘 수 있고, 불러올 때도 모두 깔끔히 ...