CII3D4 SisTerPar 05 Socket Programming
CII3D4 SisTerPar 05 Socket Programming
Materi 5:
Socket Programming
1
What is socket?
An Interface between application and network
• The application create socket
• The socket type dictates the style of communication
– reliable vs best effort
– connection oriented vs conectionless
3
Identify the Destination
• Addressing
– IP address
– hostname (resolve to IP address via DNS)
• Multiplexing
– port Server socket address
208.216.181.15:80
Client socket address
128.2.194.242:3479 FTP Server
(port 21)
5
Two essential types of socket
SOCK_STREAM SOCK_DGRAM
- TCP - UDP
- reliable delivery - unreliable delivery
- in order guaranteed - no order guarantees
- connection oriented - connectionless
6
Middleware layers
8
Python Socket Module
9
Socket Module Python
Class method Description
Socket Low-level networking interface (import)
10
sock.bind( (adrs, port) ) Bind the socket to the address and port
11
Receive data from the socket, up
sock.recvfrom( buflen[, flags] ) to buflen bytes, returning also the remote
host and port from which the data came
sock.sendto( data[, flags], addr ) Send the data through the socket
sock.getsockopt( lvl, optname ) Get the value for the specified socket option
12
import socket
import sys
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
except socket.error as err:
print ("error")
port = 80
try:
host_ip =
socket.gethostbyname('igracias.telkomuniversity.ac.id')
except socket.gaierror:
print ("there was an error resolving the host")
sys.exit()
s.connect((host_ip, port))
13
TCP Stream Comm.
Stream communication assumes that when a pair of processes
are establishing a connection, one of them plays the client role
and the other plays the server role, but thereafter they could be
peers.
14
Life Cycle
15
Ex : TCP Server
import socket
TCP_IP = '127.0.0.1'
TCP_PORT = 5005
BUFFER_SIZE = 1024
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((TCP_IP, TCP_PORT))
s.listen(1)
while 1:
conn, addr = s.accept()
print ('Alamat:', addr)
data = conn.recv(BUFFER_SIZE)
print ("data diterima:", data.decode())
conn.send(data)
conn.close()
16
Ex : TCP client
import socket
TCP_IP = '127.0.0.1'
TCP_PORT = 5005
BUFFER_SIZE = 1024
PESAN = "Hello World!"
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((TCP_IP, TCP_PORT))
s.send(PESAN.encode())
data = s.recv(BUFFER_SIZE)
s.close()
17
UDP Datagram Comm.
18
Life Cycle
19
Ex : UDP Server
import socket
UDP_IP = "127.0.0.1"
UDP_PORT = 5005
while True:
data, addr = sock.recvfrom(1024)
print (addr)
print ("pesan diterima:", data.decode())
20
Ex : UDP client
import socket
UDP_IP = "127.0.0.1"
UDP_PORT = 5005
PESAN = "Hello World!"
21
THANK YOU