본문 바로가기

기타

[python] udp 소켓 통신

반응형

python udp 소켓 통신

code : https://github.com/madscheme/introducing-python

 

udp_server.py 작성

from datetime import datetime
import socket

server_address = ('localhost', 6789)
max_size = 4096

print('Starting the server at', datetime.now())
print('Waiting for a client to call.')
server = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
server.bind(server_address)

data, client = server.recvfrom(max_size)

print('At', datetime.now(), client, 'said', data)
server.sendto(b'Are you talking to me?', client)
server.close()
A pair (host, port) is used for the AF_INET address family, where host is a string representing either a hostname in internet domain notation like 'daring.cwi.nl' or an IPv4 address like '100.50.200.5', and port is an integer.
- https://docs.python.org/3/library/socket.html

socket.SOCK_STREAM
socket.SOCK_DGRAM
These constants represent the socket types, used for the second argument to socket(). More constants may be available depending on the system. (Only SOCK_STREAM and SOCK_DGRAM appear to be generally useful.)
- https://docs.python.org/3/library/socket.html#socket.SOCK_DGRAM

 

udp_client.py 작성

import socket
from datetime import datetime

server_address = ('localhost', 6789)
max_size = 4096

print('Starting the client at', datetime.now())
client = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
client.sendto(b'Hey!', server_address)
data, server = client.recvfrom(max_size)
print('At', datetime.now(), server, 'said', data)
client.close()

python 프로그램 실행

터미널 #1

- udp 서버 실행

$ python udp_server.py
Starting the server at 2022-08-19 15:46:11.167346
Waiting for a client to call.

터미널 #2

- udp 클라이언트 실행

$ python udp_client.py
Starting the client at 2022-08-19 15:46:30.515643
At 2022-08-19 15:46:30.516865 ('127.0.0.1', 6789) said b'Are you talking to me?'

터미널#1

- udp 서버 로그 출력

At 2022-08-19 15:46:30.516803 ('127.0.0.1', 57356) said b'Hey!'

 

728x90
반응형