□ Python socket modules
Python은 두 가지 socket관련 module을 제공한다.
첫째가 Socket이고 둘째가 SocketServer인데, 내용은 다음과 같다:
1. Socket module
Python과 C에서 socket의 차이는 object에 근원을 두고 있다는 점이다. C에서는 socket call로부터 socket descriptor를 받아서 BSD API 함수의 변수로 사용된다. Python에서는 socket method가 socket object를 반환한다. 다음 표들은 Socket의 몇가지 method와 instance method들을 보여주고 있다.
2. SocketServer module
Socket server 측의 개발을 간편하게 함..
예) 다음과 같이 "Hello World" 메시지를 클라이언트에게 뿌리는 서버를 구축한다고 할 때:
=> 우선 SocketServer.StreamRequestHandler 클래스로부터 상속받는 request handler를 만든다. 서버에서 다루는 모든 내용은 이 함수의 맥락 안에서 다뤄야 한다. handle method에서는 인사하고 나간다.
Connection handler가 준비되었으므로 socket server를 만드는 일만 남았다. SocketServer.TCPServer class를 이용하여 address, port number와 request-handler method를 넘겨준다. 결과는 TCPServer object가 반환된다.
serve_forever는 서버를 시작하고 연결을 받는다.
□ Sockets programming in Python
1. Socket의 생성과 파괴
Stream socket 생성 -> streamSock = socket.socket( socket.AF_INET, socket.SOCK_STREAM )
Datagram socket 생성 -> dgramSock = socket.socket( socket.AF_INET, socket.SOCK_DGRAM )
* AF_INET : Internet Protocol(IP) socket을 요청한다는 것
* SOCK_STREAM과 SOCK_DGRAM은 각각 TCP와 UDP 소켓을 생성한다는 것
연결 닫기 -> streamSock.close()
소켓 지우기(파괴) -> del streamSock
2. Server sockets
- 소켓 생성 후 socket.bind( ('', port#) ) 와 같이 binding함.
- .bind 안에 ''와 포트번호가 하나의 ()로 묶여 들어가는 것에 주의.
- 그 다음엔 .listen( backlog ) method로 backlog 수의 connection만큼 받도록 listening함.
- 마지막으로 client가 오면 .accept()를 통해 새 연결을 형성한다.
ex)
sock = socket.socket( socket.AF_INET, socket.SOCK_STREAM )
sock.bind( ('', 2525) )
sock.listen( 5 )
newsock, (remhost, remport ) = sock.accept()
3. Client sockets
- 서버 소켓 생성하는 과정과 비슷...
ex)
sock = socket.socket( socket.AF_INET, sock.sock_DGRAM )
sock.connect( ('192.168.1.1', 2525) )
...
4. Stream sockets
- send, recv, read와 write를 통해 stream socket으로 데이터를 주고 받을 수 있다.
ex) echo server(TCP)
import socket
ex) echo client(TCP)
import socket
ex) echo client(UDP)
import socket
Python은 두 가지 socket관련 module을 제공한다.
첫째가 Socket이고 둘째가 SocketServer인데, 내용은 다음과 같다:
Class/module | Description |
Socket | Low-level networking interface (per the BSD API) |
SocketServer | Provides classes that simplify the development of network servers |
1. Socket module
Python과 C에서 socket의 차이는 object에 근원을 두고 있다는 점이다. C에서는 socket call로부터 socket descriptor를 받아서 BSD API 함수의 변수로 사용된다. Python에서는 socket method가 socket object를 반환한다. 다음 표들은 Socket의 몇가지 method와 instance method들을 보여주고 있다.
Class methods for the Socket module |
Class method | Description |
Socket | Low-level networking interface (per the BSD API) |
socket.socket(family, type) | Create and return a new socket object |
socket.getfqdn(name) | Convert a string quad dotted IP address to a fully qualified domain name (네트워크 연결 필요..) |
socket.gethostbyname(hostname) | Resolve a hostname to a string quad dotted IP address (nslookup 기능) |
socket.fromfd(fd, family, type) | Create a socket object from an existing file descriptor |
Instance methods for the Socket module |
Instance method | Description |
sock.bind( (addr, port) ) | Bind the socket to the address and port |
sock.accept() | Return a client socket (with peer address information) |
sock.listen(backlog) | Place the socket into the listening state, able to pend backlog outstanding connection requests |
sock.connect( (addr, port) ) | Connect the socket to the defined host and port |
sock.recvfrom( buflen[, flags]) | Receive data from the socket, up to buflen bytes, returning also the remote host and port from which the data came |
sock.send( data[, flags] ) | Send the data through the socket |
sock.sendto( data[, flags], addr ) | Send the data through the socket |
sock.close() | Close the socket |
sock.getsockopt( lvl, optname ) | Get the value for the specified socket option |
sock.setsockopt( lvl, optname, val) | Set the value for the specified socket option |
sock.recv( buflen[, flags] ) | Receive data from the socket, up to buflen bytes |
2. SocketServer module
Socket server 측의 개발을 간편하게 함..
예) 다음과 같이 "Hello World" 메시지를 클라이언트에게 뿌리는 서버를 구축한다고 할 때:
import SocketServer class hwRequestHandler( SocketServer.StreamRequestHandler ): def handle( self ): self.wfile.write("Hello World!\n") server = SocketServer.TCPServer( ("", 2525), hwRequestHandler ) server.serve_forever() |
Connection handler가 준비되었으므로 socket server를 만드는 일만 남았다. SocketServer.TCPServer class를 이용하여 address, port number와 request-handler method를 넘겨준다. 결과는 TCPServer object가 반환된다.
serve_forever는 서버를 시작하고 연결을 받는다.
□ Sockets programming in Python
1. Socket의 생성과 파괴
Stream socket 생성 -> streamSock = socket.socket( socket.AF_INET, socket.SOCK_STREAM )
Datagram socket 생성 -> dgramSock = socket.socket( socket.AF_INET, socket.SOCK_DGRAM )
* AF_INET : Internet Protocol(IP) socket을 요청한다는 것
* SOCK_STREAM과 SOCK_DGRAM은 각각 TCP와 UDP 소켓을 생성한다는 것
연결 닫기 -> streamSock.close()
소켓 지우기(파괴) -> del streamSock
2. Server sockets
- 소켓 생성 후 socket.bind( ('', port#) ) 와 같이 binding함.
- .bind 안에 ''와 포트번호가 하나의 ()로 묶여 들어가는 것에 주의.
- 그 다음엔 .listen( backlog ) method로 backlog 수의 connection만큼 받도록 listening함.
- 마지막으로 client가 오면 .accept()를 통해 새 연결을 형성한다.
ex)
sock = socket.socket( socket.AF_INET, socket.SOCK_STREAM )
sock.bind( ('', 2525) )
sock.listen( 5 )
newsock, (remhost, remport ) = sock.accept()
3. Client sockets
- 서버 소켓 생성하는 과정과 비슷...
ex)
sock = socket.socket( socket.AF_INET, sock.sock_DGRAM )
sock.connect( ('192.168.1.1', 2525) )
...
4. Stream sockets
- send, recv, read와 write를 통해 stream socket으로 데이터를 주고 받을 수 있다.
ex) echo server(TCP)
import socket
srvsock = socket.socket( socket.AF_INET, socket.SOCK_STREAM )
srvsock.bind( ('', 23000) )
srvsock.listen( 5 )
while 1:
clisock, (remhost, remport) = srvsock.accept() # .accept()는 새 client가 연결할 때까지 기다림(block)
str = clisock.recv(100)
clisock.send( str )
clisock.close()
ex) echo client(TCP)
import socket
clisock = socket.socket( socket.AF_INET, socket.SOCK_STREAM )
clisock.connect( ('', 23000) )
clisock.send("Hello World\n")
print clisock.recv(100)
clisock.close()
5. Datagram sockets
- Datagram sockets are disconnected by nature. -> communication requires that a destination address be provided.
- recvfrom과 sendto 메소드를 사용..
ex) echo server(UDP)
import socket
5. Datagram sockets
- Datagram sockets are disconnected by nature. -> communication requires that a destination address be provided.
- recvfrom과 sendto 메소드를 사용..
ex) echo server(UDP)
import socket
dgramSock = socket.socket( socket.AF_INET, socket.SOCK_DGRAM )
dgramSock.bind( ('', 23000) )
while 1:
msg, (addr, port) = dgramSock.recvfrom( 100 )
dgramSock.sendto( msg, (addr, port) )
ex) echo client(UDP)
import socket
dgramSock = socket.socket( socket.AF_INET, socket.SOCK_DGRAM )
dgramSock.sendto( "Hello World\n", ('', 23000) )
print dgramSock.recv( 100 )
dgramSock.close()
6. Asynchronous I/O
- 'select' method allows you to multiplex events for several sockets and for several different events.
6. Asynchronous I/O
- 'select' method allows you to multiplex events for several sockets and for several different events.