Difference between revisions of "Python3: Socket UDP"

From OnnoWiki
Jump to navigation Jump to search
(Created page with "==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...")
 
 
(One intermediate revision by the same user not shown)
Line 20: Line 20:
 
==Server==
 
==Server==
  
import socket
+
import socket
   
+
 
UDP_IP = "127.0.0.1"
+
  UDP_IP = "192.168.0.162"
UDP_PORT = 5005
+
UDP_PORT = 5005
   
+
 
sock = socket.socket(socket.AF_INET, # Internet
+
  sock = socket.socket(socket.AF_INET,   # Internet
                    socket.SOCK_DGRAM) # UDP
+
                      socket.SOCK_DGRAM) # UDP
sock.bind((UDP_IP, UDP_PORT))
+
sock.bind((UDP_IP, UDP_PORT))
   
+
 
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: %s" % data)
+
    print("received message: %s" % data)

Latest revision as of 05:29, 26 December 2020

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)