[파이썬] socket TCP/IP 소켓

In this blog post, we will explore how to use sockets in Python to establish TCP/IP connections. Sockets are a fundamental concept in network programming, allowing applications to communicate over a network using TCP/IP.

What are Sockets?

Sockets provide a communication mechanism between two entities (usually processes or threads) residing on different machines or within the same machine. They allow bidirectional data transfer, which means both the sending and receiving of data is possible.

TCP/IP 소켓 in Python

Python provides a built-in module called socket that allows us to create TCP/IP sockets and establish connections. Here’s an example of how to create a simple TCP/IP socket in Python:

import socket

# Create a TCP/IP socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

# Connect the socket to the server's IP address and port
server_address = ('localhost', 5000)
sock.connect(server_address)

# Send data to the server
message = "Hello, server!"
sock.sendall(message.encode())

# Receive data from the server
response = sock.recv(1024)
print("Received:", response.decode())

# Close the socket
sock.close()

In the above code, we import the socket module and create a TCP/IP socket using the socket.socket() method. We then connect the socket to the server’s IP address and port using the sock.connect() method.

We can send data to the server using the sock.sendall() method, which takes a string as input and sends it to the connected server. Similarly, we can receive data from the server using the sock.recv() method, which returns a byte string. We decode the received data using the decode() method to convert it into a readable format.

Finally, we close the socket using the sock.close() method to release the resources occupied by the socket.

Conclusion

Sockets are a powerful tool for network communication, and Python provides a convenient way to create TCP/IP sockets and establish connections using the socket module. We’ve covered the basics of creating a socket, connecting to a server, sending and receiving data. This is just the tip of the iceberg, and there are many more advanced features and techniques you can explore with sockets in Python.