Difference between revisions of "Python: Soket UDP"

From OnnoWiki
Jump to navigation Jump to search
 
Line 7: Line 7:
 
  MESSAGE = "Hello, World!"
 
  MESSAGE = "Hello, World!"
 
   
 
   
  print "UDP target IP:", UDP_IP
+
  print( "UDP target IP:", UDP_IP )
  print "UDP target port:", UDP_PORT
+
  print( "UDP target port:", UDP_PORT )
  print "message:", MESSAGE
+
  print( "message:", MESSAGE )
 
   
 
   
 
  sock = socket.socket(socket.AF_INET, # Internet
 
  sock = socket.socket(socket.AF_INET, # Internet
Line 30: Line 30:
 
  while True:
 
  while True:
 
     data, addr = sock.recvfrom(1024) # buffer size is 1024 bytes
 
     data, addr = sock.recvfrom(1024) # buffer size is 1024 bytes
     print "received message:", data
+
     print( "received message:", data )
  
 +
 +
==Alternatif Server==
 +
 +
nc -ul 5005
  
  

Latest revision as of 05:08, 26 December 2020

UDP Send / Client

import socket

UDP_IP = "127.0.0.1"
UDP_PORT = 5005
MESSAGE = "Hello, World!"

print( "UDP target IP:", UDP_IP )
print( "UDP target port:", UDP_PORT )
print( "message:", MESSAGE )

sock = socket.socket(socket.AF_INET, # Internet
                     socket.SOCK_DGRAM) # UDP
sock.connect(UDP_IP,UDP_PORT)
sock.sendto(MESSAGE, (UDP_IP, UDP_PORT))
sock.close()

UDP Receive / Server

import socket

UDP_IP = "127.0.0.1"
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:", data )


Alternatif Server

nc -ul 5005


Referensi