Pustaka Taratsa

Baca teks (EPUB): Python3: Socket UDP

1 bagian

Teks ini diambil langsung dari berkas EPUB; tata letak dan gambar tidak disertakan. Untuk tampilan lengkap, silakan merujuk pada dokumen asli.

Daftar isi
  1. Python3: Socket UDP
  2. Client
  3. Server

Python3: Socket UDP

Sumber: https://onnocenter.or.id/wiki/index.php/Python3:_Socket_UDP

Client

import socket

UDP_IP = "192.168.0.162"
UDP_PORT = 5005
MESSAGE = b"Hello, World!\n"

print("UDP target IP: %s" % UDP_IP)
print("UDP target port: %s" % UDP_PORT)
print("message: %s" % MESSAGE)
 
sock = socket.socket(socket.AF_INET, # Internet
                      socket.SOCK_DGRAM) # UDP
sock.sendto(MESSAGE, (UDP_IP, UDP_PORT))
sock.close()

Server

import socket
 
UDP_IP = "192.168.0.162"
UDP_PORT = 5005
 
sock = socket.socket(socket.AF_INET,    # Internet
                     socket.SOCK_DGRAM) # UDP
sock.bind((UDP_IP, UDP_PORT))
 
while True:
    data, addr = sock.recvfrom(1024)    # buffer size is 1024 bytes
    print("received message: %s" % data)