CII3D4 SisTerPar 04 Socket Programming PHV
CII3D4 SisTerPar 04 Socket Programming PHV
Materi 5:
Socket Programming
1
Apa itu socket?
Sebuah antarmuka aplikasi dan jaringan
• Application membuat socket
• Tipe sokcet mendikte cara komunikasi
– reliable vs best effort
– connection oriented vs conectionless
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
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.
Komunikasi stream mengasumsikan bahwa ketika sebuah
pasangan proses telah terjadi membuat koneksi, salah satu
berperan sebagai klien dan yang lain berperan sebagai server,
tetapi setelah itu mereka dapat menjadi 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