SlideShare a Scribd company logo
1 of 43
Download to read offline
PYTHON
SOCKET
MODULE
Moon Yong Joon
SOCKET
기본
Socket
Socket 이란
Socket이란 양방향 통신채널(endpoint)이고,
Sockets은 프로세스간, 머신들간 등의 통신을 지원
Term Description
domain Tranport 메커니즘에 사용하는 Proctocol Family
AF_INET, PF_INET, PF_UNIX, PF_X25 등
type 2개의 endpoint 사이의 커뮤니케이션 타입.
- SOCK_STREAM : connection-oriented protocols(TCP)
- SOCK_DGRAM : connectionless protocols.(UDP)
protocol a domain and type 내의 다양한 protocol를 의미. 기본값 0
hostname 실제 서버 네임 및 주소( DNS, IP )
port 각 서버가 서비스를 처리하기 위한 주소
Socket 종류
- SOCKET STREAM : SOCK_STREAM
TCP 트랜스포트 계층 프로토콜을 사용하여 통신하는 소켓
연결-지향 형태를 지원
- SOCKET DGRAM : SOCK_DGRAM
UDP 트랜스포트 계층 프로토콜을 사용하여 통신하는 소켓
신뢰적이지 못한 데이터그램 형태를 지원
Socket 구조
Socket 프로그램 구조
응용
트랜스포트
인터넷
물리
strea
m
socket
datagr
am
socket
NIC
L3/L4
응용
트랜스포트
인터넷
물리
strea
m
socket
datagr
am
socket
NIC
L3/L4
프로그램
영역
Socket 생성
Socket 객체를 생성하기 위해서는 도메인, 타입,
프로토콜을 파라미터로 받아서 생성
s = socket.socket (socket_family, socket_type, protocol=0)
domain  socket_family: AF_UNIX or AF_INET
type socket_type: SOCK_STREAM or SOCK_DGRAM.
protocol: default는 0.
AF_INET : IP version 4 or IPv4
SOCK_STREAM : TCP protocol
Client Socket 연결
클라이언트에서 서버 연결
Method Description
s.connect() TCP server 연결하기 위해 파라미터로 서버의 IP 주소
와 Port를 넘김
s.connect((TCP_IP, TCP_PORT))
Server Socket 연결
서버 내의 socket 활성화 및 클라이언트 연결
Method Description
s.bind() TCP 서버 연결
s.bind((TCP_IP, TCP_PORT))
s.listen() 클라이언트에서 이벤트 요청을 위한 TCP listener 시작
s.listen(1)
s.accept() TCP client 연결, 클라이언트 연결이 올 때까지 대기(block
ing).
conn, addr = s.accept()
Socket간 메시지 송수신
클라이언트와 서버간 TCP/UDP 메시지 송수신
Method Description
s.recv() 수신 TCP message : data = s.recv(BUFFER_SIZE)
s.send() 송신 TCP message : s.send(MESSAGE)
s.sendall() 송신 TCP message : s.sendall(MESSAGE)
s.recvfrom() 수신 UDP message
s.sendto() 송신 UDP message
s.close() socket 클로징
TCP : SOCK_STREAM
TCP 즉 연결-지향 (Connection-oriented)에 대
한 클라이언트와 서버간 메시지 송수신
UDP : SOCK_DGRAM
UDP 즉 비연결(Connectionless)에 대한 클라이
언트와 서버간 메시지 송수신
Blocking & Non-Blocking
Socket 처리는 기본 Blocking 처리
- 어떤 일이 일어나기를 기다리면서 멍하니 있는 상태
- 기본값 : socket.setblocking(1)  socket.settimeout(None)
Non-blocking 처리 : flag인자가 0
socket.setblocking(0)  socket.settimeout(0.0)
Blocking 처리 : flag 인자가 1
socket.setblocking(1)  socket.settimeout(100)
Socket 서버 정보 검색
Socket 함수
서버에 대한 host 이름이나 ip 주소 검색
Method Description
socket.gethostbyname(obj) DNS로 IP 주소 가져오기
socket.gethostname() 내부 및 외부 서버 내의 DNS 나 서버 네
임 가져오기
socket.getservbyport(obj,'t
cp')
특정 port가 처리하는 서비스 네임 가져
오기
Hostname/ipaddress 검색(1)
파이썬 함수는 인자와 결과값에 대한 타입정보를
3.5버전 이상부터 hint로 추가되어 결과값에 대한 확
인을 별도의 함수로 작성하여 확인
# return_check.py
type_str =
['str','int','float','list','dict','function','object']
def return_type(obj) :
type_check = obj.__class__.__name__
if type_check in type_str :
return True, type_check
else :
return False, type_check
Hostname/ipaddress 검색(2)
Hostname을 가지고 ip address 검색하는 함수
정의
# socket_test.py
import socket
import return_check as ret
def get_ipaddress(obj) :
'''
get ip address
'''
print " host name :", obj
ip_addr = socket.gethostbyname(obj)
print ret.return_type(ip_addr)
print " ip address :", ip_addr
Hostname/ipaddress 검색(3)
자신의 서버 및 remote 검색하기
# socket_test.py
# 자신의 PC hostname 가져오기
obj = socket.gethostname()
print ret.return_type(obj)
get_ipaddress(obj)
# localhost
obj = 'localhost'
get_ipaddress(obj)
# python org
obj = 'www.python.org'
get_ipaddress(obj)
(True, 'str')
host name : Moon
(True, 'str')
ip address : xxx.xxx.xxx.xxx
host name : localhost
(True, 'str')
ip address : 127.0.0.1
host name : www.python.org
(True, 'str')
ip address : 103.245.222.223
외부ip 호출하여 client연결
구글을 검색해서 클라이언트 서버 생성
import socket # for socket
import sys
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print "Socket successfully created"
except socket.error as err:
print "socket creation failed with error %s" %(err)
# default port for socket
port = 80
try:
host_ip = socket.gethostbyname('www.google.com')
except socket.gaierror:
# this means could not resolve the host
print "there was an error resolving the host"
sys.exit()
# connecting to the server
s.connect((host_ip,port))
print "the socket has successfully connected to google 
on port == %s" %(host_ip)
Port Protocol 정보 조회
세부 서비스 프로토콜
어플리케이션 프로토콜 및 파이선 모듈
Protocol Common function Port No Python module
HTTP Web pages 80 httplib, urllib, xmlrpclib
NNTP Usenet news 119 nntplib
FTP File transfers 20 ftplib, urllib
SMTP Sending email 25 smtplib
POP3 Fetching email 110 poplib
IMAP4 Fetching email 143 imaplib
Telnet Command lines 23 telnetlib
Gopher Document transfers 70 gopherlib, urllib
Port별 서비스 검색
TCP 내의 port별 프로토콜 서비스를 검색
# socket_test.py
def get_service(obj) :
service =socket.getservbyport(obj,'tcp')
print " port : " + str(obj) + " service name : " + service
print ' get port '
get_service(80)
get_service(53)
get_service(25)
#결과
get port
port : 80 service name : http
port : 53 service name : domain
port : 25 service name : smtp
SOCKET
생성
Socket 생성 기초
Echo 통신처리 흐름
클라이언트 서버
소
켓
소
켓
메시지 전송
메시지 전송
클라이언트에서 서버로 전송하면 그대로 전달하는
통신을 처리
서버 생성
내부의 서버를 가지고 소켓서버 생성하여 처리
import socket
HOST = 'localhost' # Symbolic name meaning all available
interfaces
PORT = 50007 # Arbitrary non-privileged port
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
s.listen(1)
while 1: # 서버 순환
conn, addr = s.accept() #클라이언트 연결
print 'Connected by', addr
while 1 : #클라이언트 순환
data = conn.recv(1024) #클라이언트로 부터 수신
if not data: break
conn.send(data) #클라이언트에 송신
conn.close()
break
s.close()
클라이언트 생성
내부의 서버를 가지고 소켓서버 생성하여 연결 처리
# Echo client program
import socket
HOST = 'localhost' # The remote host
PORT = 50007 # The same port as used by the server
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT))
while 1 :
data = raw_input('> ') #데이터를 입력창에서 받음
if not data: break
s.send(data) # 서버에 데이터 전송
data = s.recv(1024) # 서버로부터 데이터 수신
if not data: break
print 'Received', repr(data)
s.close()
Socket Exception
Socket exception 처리
import socket #for sockets
import sys #for exit
try:
#create an AF_INET, STREAM socket (TCP)
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
except socket.error, msg:
print 'Failed to create socket. Error code: ' + str(msg[0]) + ' , Error message : ' + msg[1]
sys.exit();
print 'Socket Created'
Socket 모듈 내의 error에 exception 사용
참조문서 : http://www.binarytides.com/python-socket-programming-tutorial/
Remote 서버 검색
Client socket 생성
내 서버에 socket 생성
#client_remote_test.py
import socket #for sockets
import sys #for exit
#Send some data to remote server
message = "GET / HTTP/1.1rnrn"
try :
#Set the whole string
s.sendall(message)
except socket.error:
#Send failed
print 'Send failed'
sys.exit()
print 'Message send successfully'
Client에서 외부 서버 연결
Google 서버에 연결
#client_remote_test.py
host = 'www.google.com'
port = 80
try:
remote_ip = socket.gethostbyname( host )
except socket.gaierror:
#could not resolve
print 'Hostname could not be resolved. Exiting'
sys.exit()
print 'Ip address of ' + host + ' is ' + remote_ip
#Connect to remote server
s.connect((remote_ip , port))
print 'Socket Connected to ' + host + ' on ip ' + remote_ip
Remote 연결 실행 결과
클라이언트 socket을 생성하고 remote 서버인
www.google.com 으로 접속
Client : 외부서버 메시지 전송
Google 서버로 Http 메시지 전송
#client_remote_test.py
#Send some data to remote server
message = "GET / HTTP/1.1rnrn"
try :
#Set the whole string
print 'send message ', message
s.sendall(message)
except socket.error:
#Send failed
print 'Send failed'
sys.exit()
print 'Message send successfully'
Client : 외부서버 메시지 수신
Google 서버에서 http 메시지 수신
#client_remote_test.py
#Now receive data
reply = s.recv(4096)
print 'receive message '
print reply
http 메시지 실행 결과 - 송신
www.google.com 으로 접속하여 get method
로 메시지 전송 및 수신
http 메시지 실행 결과 - 수신
www.google.com 으로 접속하여 get method
로 메시지 전송 및 수신
Socket Exception
Socket exception
Socket Exception 속성
속성 Description
socket.error 소켓관련 에러 처리
socket.herror 주소관련 에러
gethostbyname_ex() and gethostbyaddr()
socket.gaierror 주소관련 에러
getaddrinfo() and getnameinfo()
socket.timeout 타임아웃 발생에러
settimeout()
Socket 오류: 기본
Socket 생성에 대한 에러 처리
# GetRemortIP,py
# Socket 생성
import socket # for socket
import sys
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print "Socket successfully created"
except socket.error as err:
print "socket creation failed with error %s" %(err)
# default port for socket
port = 80
Socket 오류: gaierror
Google 서버에서 접속시 에러 처리
# GetRemortIP,py
# google 주소 검색
try:
host_ip = socket.gethostbyname('www.googlx.co')
except socket.gaierror, e:
# this means could not resolve the host
print "there was an error resolving the host",e
sys.exit()
# connecting to the server
s.connect((host_ip,port))
print "the socket has successfully connected to google 
on port == %s" %(host_ip)
DSN 이름을 잘
못 입력해서 오
류 발생
Socket 오류: timeout(1)
Socket 생성후에 타임아웃 정의
import socket
import sys
TCP_IP = '127.0.0.1'
TCP_PORT = 51874
BUFFER_SIZE = 1024
def test_socket_modes() :
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setblocking(1)
s.settimeout(0.5)
s.bind((TCP_IP,TCP_PORT))
s.listen(1)
while 1 :
client, address = s.accept()
while 1 :
data = client.recv(1024)
if not data: break
client.send(data)
client.close()
break
s.close()
타임아웃 세팅해서
타임아웃초과시 에
러 처리
Socket 오류: timeout(2)
Socket 실행시 타임아웃 처리
if __name__ == "__main__" :
try :
test_socket_modes()
except socket.timeout, e :
print " timeout :", e
sys.exit()
타임아웃 세팅해서
타임아웃초과시 에
러 처리

More Related Content

What's hot

Android httpclient
Android httpclientAndroid httpclient
Android httpclientallanh0526
 
HotPics 2021
HotPics 2021HotPics 2021
HotPics 2021neexemil
 
JUnit & Mockito, first steps
JUnit & Mockito, first stepsJUnit & Mockito, first steps
JUnit & Mockito, first stepsRenato Primavera
 
JavaScript Fetch API
JavaScript Fetch APIJavaScript Fetch API
JavaScript Fetch APIXcat Liu
 
Django - Python MVC Framework
Django - Python MVC FrameworkDjango - Python MVC Framework
Django - Python MVC FrameworkBala Kumar
 
exception handling in java.ppt
exception handling in java.pptexception handling in java.ppt
exception handling in java.pptVarshini62
 
TypeScript Introduction
TypeScript IntroductionTypeScript Introduction
TypeScript IntroductionDmitry Sheiko
 
Spring Framework - Core
Spring Framework - CoreSpring Framework - Core
Spring Framework - CoreDzmitry Naskou
 
Python Programming Essentials - M19 - Namespaces, Global Variables and Docstr...
Python Programming Essentials - M19 - Namespaces, Global Variables and Docstr...Python Programming Essentials - M19 - Namespaces, Global Variables and Docstr...
Python Programming Essentials - M19 - Namespaces, Global Variables and Docstr...P3 InfoTech Solutions Pvt. Ltd.
 
Exception Handling In Python | Exceptions In Python | Python Programming Tuto...
Exception Handling In Python | Exceptions In Python | Python Programming Tuto...Exception Handling In Python | Exceptions In Python | Python Programming Tuto...
Exception Handling In Python | Exceptions In Python | Python Programming Tuto...Edureka!
 
Introducing Async/Await
Introducing Async/AwaitIntroducing Async/Await
Introducing Async/AwaitValeri Karpov
 
PHP Cookies and Sessions
PHP Cookies and SessionsPHP Cookies and Sessions
PHP Cookies and SessionsNisa Soomro
 

What's hot (20)

angular fundamentals.pdf
angular fundamentals.pdfangular fundamentals.pdf
angular fundamentals.pdf
 
Context API in React
Context API in ReactContext API in React
Context API in React
 
JavaScript Promises
JavaScript PromisesJavaScript Promises
JavaScript Promises
 
Android httpclient
Android httpclientAndroid httpclient
Android httpclient
 
HotPics 2021
HotPics 2021HotPics 2021
HotPics 2021
 
Java Strings
Java StringsJava Strings
Java Strings
 
JUnit & Mockito, first steps
JUnit & Mockito, first stepsJUnit & Mockito, first steps
JUnit & Mockito, first steps
 
JavaScript Fetch API
JavaScript Fetch APIJavaScript Fetch API
JavaScript Fetch API
 
Validation controls ASP .NET
Validation controls ASP .NETValidation controls ASP .NET
Validation controls ASP .NET
 
Django - Python MVC Framework
Django - Python MVC FrameworkDjango - Python MVC Framework
Django - Python MVC Framework
 
exception handling in java.ppt
exception handling in java.pptexception handling in java.ppt
exception handling in java.ppt
 
TypeScript Introduction
TypeScript IntroductionTypeScript Introduction
TypeScript Introduction
 
Spring Framework - Core
Spring Framework - CoreSpring Framework - Core
Spring Framework - Core
 
Spring annotation
Spring annotationSpring annotation
Spring annotation
 
Why rust?
Why rust?Why rust?
Why rust?
 
Python Programming Essentials - M19 - Namespaces, Global Variables and Docstr...
Python Programming Essentials - M19 - Namespaces, Global Variables and Docstr...Python Programming Essentials - M19 - Namespaces, Global Variables and Docstr...
Python Programming Essentials - M19 - Namespaces, Global Variables and Docstr...
 
Exception Handling In Python | Exceptions In Python | Python Programming Tuto...
Exception Handling In Python | Exceptions In Python | Python Programming Tuto...Exception Handling In Python | Exceptions In Python | Python Programming Tuto...
Exception Handling In Python | Exceptions In Python | Python Programming Tuto...
 
Introducing Async/Await
Introducing Async/AwaitIntroducing Async/Await
Introducing Async/Await
 
PHP Cookies and Sessions
PHP Cookies and SessionsPHP Cookies and Sessions
PHP Cookies and Sessions
 
Python
PythonPython
Python
 

Viewers also liked

파이썬+객체지향+이해하기 20160131
파이썬+객체지향+이해하기 20160131파이썬+객체지향+이해하기 20160131
파이썬+객체지향+이해하기 20160131Yong Joon Moon
 
05 1 통신프로토콜과표준화-최근표준화협력방향
05 1 통신프로토콜과표준화-최근표준화협력방향05 1 통신프로토콜과표준화-최근표준화협력방향
05 1 통신프로토콜과표준화-최근표준화협력방향Youngsun Lee
 
Python - A Comprehensive Programming Language
Python - A Comprehensive Programming LanguagePython - A Comprehensive Programming Language
Python - A Comprehensive Programming LanguageTsungWei Hu
 
파이썬+클래스+구조+이해하기 20160310
파이썬+클래스+구조+이해하기 20160310파이썬+클래스+구조+이해하기 20160310
파이썬+클래스+구조+이해하기 20160310Yong Joon Moon
 
Python Programming - I. Introduction
Python Programming - I. IntroductionPython Programming - I. Introduction
Python Programming - I. IntroductionRanel Padon
 
Reflect package 사용하기
Reflect package 사용하기Reflect package 사용하기
Reflect package 사용하기Yong Joon Moon
 
파이썬 Datetime 이해하기
파이썬 Datetime 이해하기파이썬 Datetime 이해하기
파이썬 Datetime 이해하기Yong Joon Moon
 
파이썬 namespace Binding 이해하기
파이썬 namespace Binding 이해하기 파이썬 namespace Binding 이해하기
파이썬 namespace Binding 이해하기 Yong Joon Moon
 
파이썬정리 20160130
파이썬정리 20160130파이썬정리 20160130
파이썬정리 20160130Yong Joon Moon
 
Switchable Map APIs with Drupal
Switchable Map APIs with DrupalSwitchable Map APIs with Drupal
Switchable Map APIs with DrupalRanel Padon
 
파이썬 객체 클래스 이해하기
파이썬  객체 클래스 이해하기파이썬  객체 클래스 이해하기
파이썬 객체 클래스 이해하기Yong Joon Moon
 
파이썬 함수 이해하기
파이썬 함수 이해하기 파이썬 함수 이해하기
파이썬 함수 이해하기 Yong Joon Moon
 
파이썬+정규표현식+이해하기 20160301
파이썬+정규표현식+이해하기 20160301파이썬+정규표현식+이해하기 20160301
파이썬+정규표현식+이해하기 20160301Yong Joon Moon
 
141103 최창원 파이썬 확장 프로그래밍
141103 최창원 파이썬 확장 프로그래밍141103 최창원 파이썬 확장 프로그래밍
141103 최창원 파이썬 확장 프로그래밍Changwon Choe
 
파이썬 class 및 인스턴스 생성 이해하기
파이썬 class 및 인스턴스 생성 이해하기파이썬 class 및 인스턴스 생성 이해하기
파이썬 class 및 인스턴스 생성 이해하기Yong Joon Moon
 
파이썬 문자열 이해하기
파이썬 문자열 이해하기파이썬 문자열 이해하기
파이썬 문자열 이해하기Yong Joon Moon
 
파이썬 sqlite 이해하기
파이썬 sqlite 이해하기파이썬 sqlite 이해하기
파이썬 sqlite 이해하기Yong Joon Moon
 
Python Programming - IV. Program Components (Functions, Classes, Modules, Pac...
Python Programming - IV. Program Components (Functions, Classes, Modules, Pac...Python Programming - IV. Program Components (Functions, Classes, Modules, Pac...
Python Programming - IV. Program Components (Functions, Classes, Modules, Pac...Ranel Padon
 

Viewers also liked (20)

파이썬+객체지향+이해하기 20160131
파이썬+객체지향+이해하기 20160131파이썬+객체지향+이해하기 20160131
파이썬+객체지향+이해하기 20160131
 
05 1 통신프로토콜과표준화-최근표준화협력방향
05 1 통신프로토콜과표준화-최근표준화협력방향05 1 통신프로토콜과표준화-최근표준화협력방향
05 1 통신프로토콜과표준화-최근표준화협력방향
 
Python session 8
Python session 8Python session 8
Python session 8
 
Net prog
Net progNet prog
Net prog
 
Python - A Comprehensive Programming Language
Python - A Comprehensive Programming LanguagePython - A Comprehensive Programming Language
Python - A Comprehensive Programming Language
 
파이썬+클래스+구조+이해하기 20160310
파이썬+클래스+구조+이해하기 20160310파이썬+클래스+구조+이해하기 20160310
파이썬+클래스+구조+이해하기 20160310
 
Python Programming - I. Introduction
Python Programming - I. IntroductionPython Programming - I. Introduction
Python Programming - I. Introduction
 
Reflect package 사용하기
Reflect package 사용하기Reflect package 사용하기
Reflect package 사용하기
 
파이썬 Datetime 이해하기
파이썬 Datetime 이해하기파이썬 Datetime 이해하기
파이썬 Datetime 이해하기
 
파이썬 namespace Binding 이해하기
파이썬 namespace Binding 이해하기 파이썬 namespace Binding 이해하기
파이썬 namespace Binding 이해하기
 
파이썬정리 20160130
파이썬정리 20160130파이썬정리 20160130
파이썬정리 20160130
 
Switchable Map APIs with Drupal
Switchable Map APIs with DrupalSwitchable Map APIs with Drupal
Switchable Map APIs with Drupal
 
파이썬 객체 클래스 이해하기
파이썬  객체 클래스 이해하기파이썬  객체 클래스 이해하기
파이썬 객체 클래스 이해하기
 
파이썬 함수 이해하기
파이썬 함수 이해하기 파이썬 함수 이해하기
파이썬 함수 이해하기
 
파이썬+정규표현식+이해하기 20160301
파이썬+정규표현식+이해하기 20160301파이썬+정규표현식+이해하기 20160301
파이썬+정규표현식+이해하기 20160301
 
141103 최창원 파이썬 확장 프로그래밍
141103 최창원 파이썬 확장 프로그래밍141103 최창원 파이썬 확장 프로그래밍
141103 최창원 파이썬 확장 프로그래밍
 
파이썬 class 및 인스턴스 생성 이해하기
파이썬 class 및 인스턴스 생성 이해하기파이썬 class 및 인스턴스 생성 이해하기
파이썬 class 및 인스턴스 생성 이해하기
 
파이썬 문자열 이해하기
파이썬 문자열 이해하기파이썬 문자열 이해하기
파이썬 문자열 이해하기
 
파이썬 sqlite 이해하기
파이썬 sqlite 이해하기파이썬 sqlite 이해하기
파이썬 sqlite 이해하기
 
Python Programming - IV. Program Components (Functions, Classes, Modules, Pac...
Python Programming - IV. Program Components (Functions, Classes, Modules, Pac...Python Programming - IV. Program Components (Functions, Classes, Modules, Pac...
Python Programming - IV. Program Components (Functions, Classes, Modules, Pac...
 

Similar to 파이썬+네트워크 20160210

리눅스 소켓 프로그래밍 기초
리눅스 소켓 프로그래밍 기초리눅스 소켓 프로그래밍 기초
리눅스 소켓 프로그래밍 기초Yu Yongwoo
 
TCP echo 서버 및 클라이언트 예제 스터디
TCP echo 서버 및 클라이언트 예제 스터디TCP echo 서버 및 클라이언트 예제 스터디
TCP echo 서버 및 클라이언트 예제 스터디quxn6
 
Python socket programming
Python socket programmingPython socket programming
Python socket programmingTae Young Lee
 
(C#,네트워크강좌)간단한 TCP 클라이언트/서버 구현, 멀티쓰레드 기반 에코우 클라이언트/서버_C추천#/WPF/자마린실무교육학원
(C#,네트워크강좌)간단한 TCP 클라이언트/서버 구현, 멀티쓰레드 기반 에코우 클라이언트/서버_C추천#/WPF/자마린실무교육학원(C#,네트워크강좌)간단한 TCP 클라이언트/서버 구현, 멀티쓰레드 기반 에코우 클라이언트/서버_C추천#/WPF/자마린실무교육학원
(C#,네트워크강좌)간단한 TCP 클라이언트/서버 구현, 멀티쓰레드 기반 에코우 클라이언트/서버_C추천#/WPF/자마린실무교육학원탑크리에듀(구로디지털단지역3번출구 2분거리)
 
[NodeJS] - NET 모듈 소개
[NodeJS] - NET 모듈 소개[NodeJS] - NET 모듈 소개
[NodeJS] - NET 모듈 소개문학청년
 
Python Network Programming
Python Network ProgrammingPython Network Programming
Python Network ProgrammingTae Young Lee
 
Blockchain 4th dapp programming
Blockchain 4th dapp programmingBlockchain 4th dapp programming
Blockchain 4th dapp programmingihpark92
 
Python으로 채팅 구현하기
Python으로 채팅 구현하기Python으로 채팅 구현하기
Python으로 채팅 구현하기Tae Young Lee
 
11_웹서비스활용
11_웹서비스활용11_웹서비스활용
11_웹서비스활용noerror
 
KGC 2016 오픈소스 네트워크 엔진 Super socket 사용하기
KGC 2016 오픈소스 네트워크 엔진 Super socket 사용하기KGC 2016 오픈소스 네트워크 엔진 Super socket 사용하기
KGC 2016 오픈소스 네트워크 엔진 Super socket 사용하기흥배 최
 
소켓프로그래밍 기초요약
소켓프로그래밍 기초요약소켓프로그래밍 기초요약
소켓프로그래밍 기초요약세빈 정
 
소켓 주소 구조체 다루기(윈도우 네트워크 프로그래밍)
소켓 주소 구조체 다루기(윈도우 네트워크 프로그래밍)소켓 주소 구조체 다루기(윈도우 네트워크 프로그래밍)
소켓 주소 구조체 다루기(윈도우 네트워크 프로그래밍)문익 장
 
[KGC 2011]Boost 라이브러리와 C++11
[KGC 2011]Boost 라이브러리와 C++11[KGC 2011]Boost 라이브러리와 C++11
[KGC 2011]Boost 라이브러리와 C++11흥배 최
 
TCP/IP Protocol - JAVA
TCP/IP Protocol - JAVATCP/IP Protocol - JAVA
TCP/IP Protocol - JAVAcooddy
 
Google Protocol buffer
Google Protocol bufferGoogle Protocol buffer
Google Protocol bufferknight1128
 
세션3. geth 클라이언트 실습 및 모니터링과 시각화
세션3. geth 클라이언트 실습 및 모니터링과 시각화세션3. geth 클라이언트 실습 및 모니터링과 시각화
세션3. geth 클라이언트 실습 및 모니터링과 시각화Jay JH Park
 
Wiznet Academy - WizFi250 기초교육 및 실습
Wiznet Academy - WizFi250 기초교육 및 실습Wiznet Academy - WizFi250 기초교육 및 실습
Wiznet Academy - WizFi250 기초교육 및 실습Steve Kim
 
하이퍼레저 패브릭 데이터 구조
하이퍼레저 패브릭 데이터 구조하이퍼레저 패브릭 데이터 구조
하이퍼레저 패브릭 데이터 구조Logpresso
 
세션5. web3.js와 Node.js 를 사용한 dApp 개발
세션5. web3.js와 Node.js 를 사용한 dApp 개발세션5. web3.js와 Node.js 를 사용한 dApp 개발
세션5. web3.js와 Node.js 를 사용한 dApp 개발Jay JH Park
 
막하는 스터디 첫 번째 만남 Node.js
막하는 스터디 첫 번째 만남 Node.js막하는 스터디 첫 번째 만남 Node.js
막하는 스터디 첫 번째 만남 Node.js연웅 조
 

Similar to 파이썬+네트워크 20160210 (20)

리눅스 소켓 프로그래밍 기초
리눅스 소켓 프로그래밍 기초리눅스 소켓 프로그래밍 기초
리눅스 소켓 프로그래밍 기초
 
TCP echo 서버 및 클라이언트 예제 스터디
TCP echo 서버 및 클라이언트 예제 스터디TCP echo 서버 및 클라이언트 예제 스터디
TCP echo 서버 및 클라이언트 예제 스터디
 
Python socket programming
Python socket programmingPython socket programming
Python socket programming
 
(C#,네트워크강좌)간단한 TCP 클라이언트/서버 구현, 멀티쓰레드 기반 에코우 클라이언트/서버_C추천#/WPF/자마린실무교육학원
(C#,네트워크강좌)간단한 TCP 클라이언트/서버 구현, 멀티쓰레드 기반 에코우 클라이언트/서버_C추천#/WPF/자마린실무교육학원(C#,네트워크강좌)간단한 TCP 클라이언트/서버 구현, 멀티쓰레드 기반 에코우 클라이언트/서버_C추천#/WPF/자마린실무교육학원
(C#,네트워크강좌)간단한 TCP 클라이언트/서버 구현, 멀티쓰레드 기반 에코우 클라이언트/서버_C추천#/WPF/자마린실무교육학원
 
[NodeJS] - NET 모듈 소개
[NodeJS] - NET 모듈 소개[NodeJS] - NET 모듈 소개
[NodeJS] - NET 모듈 소개
 
Python Network Programming
Python Network ProgrammingPython Network Programming
Python Network Programming
 
Blockchain 4th dapp programming
Blockchain 4th dapp programmingBlockchain 4th dapp programming
Blockchain 4th dapp programming
 
Python으로 채팅 구현하기
Python으로 채팅 구현하기Python으로 채팅 구현하기
Python으로 채팅 구현하기
 
11_웹서비스활용
11_웹서비스활용11_웹서비스활용
11_웹서비스활용
 
KGC 2016 오픈소스 네트워크 엔진 Super socket 사용하기
KGC 2016 오픈소스 네트워크 엔진 Super socket 사용하기KGC 2016 오픈소스 네트워크 엔진 Super socket 사용하기
KGC 2016 오픈소스 네트워크 엔진 Super socket 사용하기
 
소켓프로그래밍 기초요약
소켓프로그래밍 기초요약소켓프로그래밍 기초요약
소켓프로그래밍 기초요약
 
소켓 주소 구조체 다루기(윈도우 네트워크 프로그래밍)
소켓 주소 구조체 다루기(윈도우 네트워크 프로그래밍)소켓 주소 구조체 다루기(윈도우 네트워크 프로그래밍)
소켓 주소 구조체 다루기(윈도우 네트워크 프로그래밍)
 
[KGC 2011]Boost 라이브러리와 C++11
[KGC 2011]Boost 라이브러리와 C++11[KGC 2011]Boost 라이브러리와 C++11
[KGC 2011]Boost 라이브러리와 C++11
 
TCP/IP Protocol - JAVA
TCP/IP Protocol - JAVATCP/IP Protocol - JAVA
TCP/IP Protocol - JAVA
 
Google Protocol buffer
Google Protocol bufferGoogle Protocol buffer
Google Protocol buffer
 
세션3. geth 클라이언트 실습 및 모니터링과 시각화
세션3. geth 클라이언트 실습 및 모니터링과 시각화세션3. geth 클라이언트 실습 및 모니터링과 시각화
세션3. geth 클라이언트 실습 및 모니터링과 시각화
 
Wiznet Academy - WizFi250 기초교육 및 실습
Wiznet Academy - WizFi250 기초교육 및 실습Wiznet Academy - WizFi250 기초교육 및 실습
Wiznet Academy - WizFi250 기초교육 및 실습
 
하이퍼레저 패브릭 데이터 구조
하이퍼레저 패브릭 데이터 구조하이퍼레저 패브릭 데이터 구조
하이퍼레저 패브릭 데이터 구조
 
세션5. web3.js와 Node.js 를 사용한 dApp 개발
세션5. web3.js와 Node.js 를 사용한 dApp 개발세션5. web3.js와 Node.js 를 사용한 dApp 개발
세션5. web3.js와 Node.js 를 사용한 dApp 개발
 
막하는 스터디 첫 번째 만남 Node.js
막하는 스터디 첫 번째 만남 Node.js막하는 스터디 첫 번째 만남 Node.js
막하는 스터디 첫 번째 만남 Node.js
 

More from Yong Joon Moon

Scala companion object
Scala companion objectScala companion object
Scala companion objectYong Joon Moon
 
Scala block expression
Scala block expressionScala block expression
Scala block expressionYong Joon Moon
 
Scala self type inheritance
Scala self type inheritanceScala self type inheritance
Scala self type inheritanceYong Joon Moon
 
Scala type class pattern
Scala type class patternScala type class pattern
Scala type class patternYong Joon Moon
 
Scala nested function generic function
Scala nested function generic functionScala nested function generic function
Scala nested function generic functionYong Joon Moon
 
스칼라 클래스 이해하기 _Scala class understanding
스칼라 클래스 이해하기 _Scala class understanding스칼라 클래스 이해하기 _Scala class understanding
스칼라 클래스 이해하기 _Scala class understandingYong Joon Moon
 
파이썬 반복자 생성자 이해하기
파이썬 반복자 생성자 이해하기파이썬 반복자 생성자 이해하기
파이썬 반복자 생성자 이해하기Yong Joon Moon
 
파이썬 프로퍼티 디스크립터 이해하기
파이썬 프로퍼티 디스크립터 이해하기파이썬 프로퍼티 디스크립터 이해하기
파이썬 프로퍼티 디스크립터 이해하기Yong Joon Moon
 
파이썬 플라스크 이해하기
파이썬 플라스크 이해하기 파이썬 플라스크 이해하기
파이썬 플라스크 이해하기 Yong Joon Moon
 
파이썬 내부 데이터 검색 방법
파이썬 내부 데이터 검색 방법파이썬 내부 데이터 검색 방법
파이썬 내부 데이터 검색 방법Yong Joon Moon
 
파이썬 Xml 이해하기
파이썬 Xml 이해하기파이썬 Xml 이해하기
파이썬 Xml 이해하기Yong Joon Moon
 

More from Yong Joon Moon (20)

rust ownership
rust ownership rust ownership
rust ownership
 
Scala namespace scope
Scala namespace scopeScala namespace scope
Scala namespace scope
 
Scala companion object
Scala companion objectScala companion object
Scala companion object
 
Scala block expression
Scala block expressionScala block expression
Scala block expression
 
Scala self type inheritance
Scala self type inheritanceScala self type inheritance
Scala self type inheritance
 
Scala variable
Scala variableScala variable
Scala variable
 
Scala type class pattern
Scala type class patternScala type class pattern
Scala type class pattern
 
Scala match pattern
Scala match patternScala match pattern
Scala match pattern
 
Scala implicit
Scala implicitScala implicit
Scala implicit
 
Scala type args
Scala type argsScala type args
Scala type args
 
Scala trait usage
Scala trait usageScala trait usage
Scala trait usage
 
Scala nested function generic function
Scala nested function generic functionScala nested function generic function
Scala nested function generic function
 
Scala dir processing
Scala dir processingScala dir processing
Scala dir processing
 
Scala syntax function
Scala syntax functionScala syntax function
Scala syntax function
 
스칼라 클래스 이해하기 _Scala class understanding
스칼라 클래스 이해하기 _Scala class understanding스칼라 클래스 이해하기 _Scala class understanding
스칼라 클래스 이해하기 _Scala class understanding
 
파이썬 반복자 생성자 이해하기
파이썬 반복자 생성자 이해하기파이썬 반복자 생성자 이해하기
파이썬 반복자 생성자 이해하기
 
파이썬 프로퍼티 디스크립터 이해하기
파이썬 프로퍼티 디스크립터 이해하기파이썬 프로퍼티 디스크립터 이해하기
파이썬 프로퍼티 디스크립터 이해하기
 
파이썬 플라스크 이해하기
파이썬 플라스크 이해하기 파이썬 플라스크 이해하기
파이썬 플라스크 이해하기
 
파이썬 내부 데이터 검색 방법
파이썬 내부 데이터 검색 방법파이썬 내부 데이터 검색 방법
파이썬 내부 데이터 검색 방법
 
파이썬 Xml 이해하기
파이썬 Xml 이해하기파이썬 Xml 이해하기
파이썬 Xml 이해하기
 

파이썬+네트워크 20160210

  • 4. Socket 이란 Socket이란 양방향 통신채널(endpoint)이고, Sockets은 프로세스간, 머신들간 등의 통신을 지원 Term Description domain Tranport 메커니즘에 사용하는 Proctocol Family AF_INET, PF_INET, PF_UNIX, PF_X25 등 type 2개의 endpoint 사이의 커뮤니케이션 타입. - SOCK_STREAM : connection-oriented protocols(TCP) - SOCK_DGRAM : connectionless protocols.(UDP) protocol a domain and type 내의 다양한 protocol를 의미. 기본값 0 hostname 실제 서버 네임 및 주소( DNS, IP ) port 각 서버가 서비스를 처리하기 위한 주소
  • 5. Socket 종류 - SOCKET STREAM : SOCK_STREAM TCP 트랜스포트 계층 프로토콜을 사용하여 통신하는 소켓 연결-지향 형태를 지원 - SOCKET DGRAM : SOCK_DGRAM UDP 트랜스포트 계층 프로토콜을 사용하여 통신하는 소켓 신뢰적이지 못한 데이터그램 형태를 지원
  • 6. Socket 구조 Socket 프로그램 구조 응용 트랜스포트 인터넷 물리 strea m socket datagr am socket NIC L3/L4 응용 트랜스포트 인터넷 물리 strea m socket datagr am socket NIC L3/L4 프로그램 영역
  • 7. Socket 생성 Socket 객체를 생성하기 위해서는 도메인, 타입, 프로토콜을 파라미터로 받아서 생성 s = socket.socket (socket_family, socket_type, protocol=0) domain  socket_family: AF_UNIX or AF_INET type socket_type: SOCK_STREAM or SOCK_DGRAM. protocol: default는 0. AF_INET : IP version 4 or IPv4 SOCK_STREAM : TCP protocol
  • 8. Client Socket 연결 클라이언트에서 서버 연결 Method Description s.connect() TCP server 연결하기 위해 파라미터로 서버의 IP 주소 와 Port를 넘김 s.connect((TCP_IP, TCP_PORT))
  • 9. Server Socket 연결 서버 내의 socket 활성화 및 클라이언트 연결 Method Description s.bind() TCP 서버 연결 s.bind((TCP_IP, TCP_PORT)) s.listen() 클라이언트에서 이벤트 요청을 위한 TCP listener 시작 s.listen(1) s.accept() TCP client 연결, 클라이언트 연결이 올 때까지 대기(block ing). conn, addr = s.accept()
  • 10. Socket간 메시지 송수신 클라이언트와 서버간 TCP/UDP 메시지 송수신 Method Description s.recv() 수신 TCP message : data = s.recv(BUFFER_SIZE) s.send() 송신 TCP message : s.send(MESSAGE) s.sendall() 송신 TCP message : s.sendall(MESSAGE) s.recvfrom() 수신 UDP message s.sendto() 송신 UDP message s.close() socket 클로징
  • 11. TCP : SOCK_STREAM TCP 즉 연결-지향 (Connection-oriented)에 대 한 클라이언트와 서버간 메시지 송수신
  • 12. UDP : SOCK_DGRAM UDP 즉 비연결(Connectionless)에 대한 클라이 언트와 서버간 메시지 송수신
  • 13. Blocking & Non-Blocking Socket 처리는 기본 Blocking 처리 - 어떤 일이 일어나기를 기다리면서 멍하니 있는 상태 - 기본값 : socket.setblocking(1)  socket.settimeout(None) Non-blocking 처리 : flag인자가 0 socket.setblocking(0)  socket.settimeout(0.0) Blocking 처리 : flag 인자가 1 socket.setblocking(1)  socket.settimeout(100)
  • 15. Socket 함수 서버에 대한 host 이름이나 ip 주소 검색 Method Description socket.gethostbyname(obj) DNS로 IP 주소 가져오기 socket.gethostname() 내부 및 외부 서버 내의 DNS 나 서버 네 임 가져오기 socket.getservbyport(obj,'t cp') 특정 port가 처리하는 서비스 네임 가져 오기
  • 16. Hostname/ipaddress 검색(1) 파이썬 함수는 인자와 결과값에 대한 타입정보를 3.5버전 이상부터 hint로 추가되어 결과값에 대한 확 인을 별도의 함수로 작성하여 확인 # return_check.py type_str = ['str','int','float','list','dict','function','object'] def return_type(obj) : type_check = obj.__class__.__name__ if type_check in type_str : return True, type_check else : return False, type_check
  • 17. Hostname/ipaddress 검색(2) Hostname을 가지고 ip address 검색하는 함수 정의 # socket_test.py import socket import return_check as ret def get_ipaddress(obj) : ''' get ip address ''' print " host name :", obj ip_addr = socket.gethostbyname(obj) print ret.return_type(ip_addr) print " ip address :", ip_addr
  • 18. Hostname/ipaddress 검색(3) 자신의 서버 및 remote 검색하기 # socket_test.py # 자신의 PC hostname 가져오기 obj = socket.gethostname() print ret.return_type(obj) get_ipaddress(obj) # localhost obj = 'localhost' get_ipaddress(obj) # python org obj = 'www.python.org' get_ipaddress(obj) (True, 'str') host name : Moon (True, 'str') ip address : xxx.xxx.xxx.xxx host name : localhost (True, 'str') ip address : 127.0.0.1 host name : www.python.org (True, 'str') ip address : 103.245.222.223
  • 19. 외부ip 호출하여 client연결 구글을 검색해서 클라이언트 서버 생성 import socket # for socket import sys try: s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) print "Socket successfully created" except socket.error as err: print "socket creation failed with error %s" %(err) # default port for socket port = 80 try: host_ip = socket.gethostbyname('www.google.com') except socket.gaierror: # this means could not resolve the host print "there was an error resolving the host" sys.exit() # connecting to the server s.connect((host_ip,port)) print "the socket has successfully connected to google on port == %s" %(host_ip)
  • 21. 세부 서비스 프로토콜 어플리케이션 프로토콜 및 파이선 모듈 Protocol Common function Port No Python module HTTP Web pages 80 httplib, urllib, xmlrpclib NNTP Usenet news 119 nntplib FTP File transfers 20 ftplib, urllib SMTP Sending email 25 smtplib POP3 Fetching email 110 poplib IMAP4 Fetching email 143 imaplib Telnet Command lines 23 telnetlib Gopher Document transfers 70 gopherlib, urllib
  • 22. Port별 서비스 검색 TCP 내의 port별 프로토콜 서비스를 검색 # socket_test.py def get_service(obj) : service =socket.getservbyport(obj,'tcp') print " port : " + str(obj) + " service name : " + service print ' get port ' get_service(80) get_service(53) get_service(25) #결과 get port port : 80 service name : http port : 53 service name : domain port : 25 service name : smtp
  • 25. Echo 통신처리 흐름 클라이언트 서버 소 켓 소 켓 메시지 전송 메시지 전송 클라이언트에서 서버로 전송하면 그대로 전달하는 통신을 처리
  • 26. 서버 생성 내부의 서버를 가지고 소켓서버 생성하여 처리 import socket HOST = 'localhost' # Symbolic name meaning all available interfaces PORT = 50007 # Arbitrary non-privileged port s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind((HOST, PORT)) s.listen(1) while 1: # 서버 순환 conn, addr = s.accept() #클라이언트 연결 print 'Connected by', addr while 1 : #클라이언트 순환 data = conn.recv(1024) #클라이언트로 부터 수신 if not data: break conn.send(data) #클라이언트에 송신 conn.close() break s.close()
  • 27. 클라이언트 생성 내부의 서버를 가지고 소켓서버 생성하여 연결 처리 # Echo client program import socket HOST = 'localhost' # The remote host PORT = 50007 # The same port as used by the server s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((HOST, PORT)) while 1 : data = raw_input('> ') #데이터를 입력창에서 받음 if not data: break s.send(data) # 서버에 데이터 전송 data = s.recv(1024) # 서버로부터 데이터 수신 if not data: break print 'Received', repr(data) s.close()
  • 29. Socket exception 처리 import socket #for sockets import sys #for exit try: #create an AF_INET, STREAM socket (TCP) s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) except socket.error, msg: print 'Failed to create socket. Error code: ' + str(msg[0]) + ' , Error message : ' + msg[1] sys.exit(); print 'Socket Created' Socket 모듈 내의 error에 exception 사용
  • 31. Client socket 생성 내 서버에 socket 생성 #client_remote_test.py import socket #for sockets import sys #for exit #Send some data to remote server message = "GET / HTTP/1.1rnrn" try : #Set the whole string s.sendall(message) except socket.error: #Send failed print 'Send failed' sys.exit() print 'Message send successfully'
  • 32. Client에서 외부 서버 연결 Google 서버에 연결 #client_remote_test.py host = 'www.google.com' port = 80 try: remote_ip = socket.gethostbyname( host ) except socket.gaierror: #could not resolve print 'Hostname could not be resolved. Exiting' sys.exit() print 'Ip address of ' + host + ' is ' + remote_ip #Connect to remote server s.connect((remote_ip , port)) print 'Socket Connected to ' + host + ' on ip ' + remote_ip
  • 33. Remote 연결 실행 결과 클라이언트 socket을 생성하고 remote 서버인 www.google.com 으로 접속
  • 34. Client : 외부서버 메시지 전송 Google 서버로 Http 메시지 전송 #client_remote_test.py #Send some data to remote server message = "GET / HTTP/1.1rnrn" try : #Set the whole string print 'send message ', message s.sendall(message) except socket.error: #Send failed print 'Send failed' sys.exit() print 'Message send successfully'
  • 35. Client : 외부서버 메시지 수신 Google 서버에서 http 메시지 수신 #client_remote_test.py #Now receive data reply = s.recv(4096) print 'receive message ' print reply
  • 36. http 메시지 실행 결과 - 송신 www.google.com 으로 접속하여 get method 로 메시지 전송 및 수신
  • 37. http 메시지 실행 결과 - 수신 www.google.com 으로 접속하여 get method 로 메시지 전송 및 수신
  • 39. Socket exception Socket Exception 속성 속성 Description socket.error 소켓관련 에러 처리 socket.herror 주소관련 에러 gethostbyname_ex() and gethostbyaddr() socket.gaierror 주소관련 에러 getaddrinfo() and getnameinfo() socket.timeout 타임아웃 발생에러 settimeout()
  • 40. Socket 오류: 기본 Socket 생성에 대한 에러 처리 # GetRemortIP,py # Socket 생성 import socket # for socket import sys try: s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) print "Socket successfully created" except socket.error as err: print "socket creation failed with error %s" %(err) # default port for socket port = 80
  • 41. Socket 오류: gaierror Google 서버에서 접속시 에러 처리 # GetRemortIP,py # google 주소 검색 try: host_ip = socket.gethostbyname('www.googlx.co') except socket.gaierror, e: # this means could not resolve the host print "there was an error resolving the host",e sys.exit() # connecting to the server s.connect((host_ip,port)) print "the socket has successfully connected to google on port == %s" %(host_ip) DSN 이름을 잘 못 입력해서 오 류 발생
  • 42. Socket 오류: timeout(1) Socket 생성후에 타임아웃 정의 import socket import sys TCP_IP = '127.0.0.1' TCP_PORT = 51874 BUFFER_SIZE = 1024 def test_socket_modes() : s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.setblocking(1) s.settimeout(0.5) s.bind((TCP_IP,TCP_PORT)) s.listen(1) while 1 : client, address = s.accept() while 1 : data = client.recv(1024) if not data: break client.send(data) client.close() break s.close() 타임아웃 세팅해서 타임아웃초과시 에 러 처리
  • 43. Socket 오류: timeout(2) Socket 실행시 타임아웃 처리 if __name__ == "__main__" : try : test_socket_modes() except socket.timeout, e : print " timeout :", e sys.exit() 타임아웃 세팅해서 타임아웃초과시 에 러 처리