[파이썬] socket UDP 소켓

In this blog post, we will explore how to use UDP sockets in Python to establish communication between a client and a server. UDP (User Datagram Protocol) is a low-latency, connectionless protocol that allows for fast and simple communication between two endpoints.

Setting up the Server

To create a UDP server in Python, we first need to import the necessary socket module:

import socket

Next, we create a UDP socket using the socket.socket() function and specify the socket type as socket.SOCK_DGRAM:

server_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

We also need to bind the socket to a specific IP address and port number using the bind() method:

server_socket.bind(("0.0.0.0", 8888))

Here, we bind the server socket to all available network interfaces (0.0.0.0) and port 8888.

Finally, we can start receiving messages from the client using the recvfrom() method, which returns the received data and the address of the client:

data, client_address = server_socket.recvfrom(1024)
print(f"Received message: {data.decode()} from {client_address}")

Make sure to decode the received data using the appropriate encoding, such as data.decode("utf-8").

Setting up the Client

To create a UDP client in Python, we follow similar steps as the server. First, import the socket module:

import socket

Next, create a UDP socket:

client_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

We can then send a message to the server using the sendto() method, specifying the server’s IP address and port number:

message = "Hello server!"
client_socket.sendto(message.encode(), ("127.0.0.1", 8888))

Here, we encode the message using the encode() method to convert it to bytes.

Conclusion

In this blog post, we have seen how to use UDP sockets in Python to establish communication between a client and a server. UDP sockets are a lightweight and efficient way to send and receive data over a network, making them ideal for applications that prioritize low-latency communication. Remember, UDP is a connectionless protocol, so it does not guarantee delivery or order of messages. However, with proper error handling and validation, UDP sockets can be used effectively in various applications.