[파이썬] socket 연결 대기하기

When developing a network application, it is often necessary to create a socket server that listens for incoming connections. In Python, you can accomplish this by using the socket module. Let’s explore how to implement socket connection waiting in Python.

Example Code

import socket

HOST = 'localhost'  # Replace with your desired host
PORT = 1234  # Replace with your desired port

# Create a socket object
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

# Bind the socket to a specific host and port
server_socket.bind((HOST, PORT))

# Listen for incoming connections
server_socket.listen()

print(f"Server is listening on {HOST}:{PORT}")

# Accept incoming connections
client_socket, client_address = server_socket.accept()

print(f"Connected to {client_address}")

# Handle the client connection
# Perform your desired operations here

# Close the client socket
client_socket.close()

# Close the server socket
server_socket.close()

Explanation

  1. Import the socket module.

  2. Set the HOST variable to the desired host that you want the server to listen on. It can be an IP address or a hostname.

  3. Set the PORT variable to the desired port number that the server should listen on.

  4. Create a server socket object using socket.socket(socket.AF_INET, socket.SOCK_STREAM). This will create a TCP socket.

  5. Bind the socket to the specified host and port using server_socket.bind((HOST, PORT)).

  6. Start listening for incoming connections using server_socket.listen().

  7. Print a message to indicate that the server is listening.

  8. Accept incoming connections using client_socket, client_address = server_socket.accept(). This line will block until a client connects.

  9. Print a message to indicate that the server has successfully connected to the client.

  10. Handle the client connection by performing your desired operations within the designated area.

  11. Close the client socket using client_socket.close().

  12. Close the server socket using server_socket.close().

You can run this code on your machine and test it by connecting to the specified host and port using a client implementation. This example demonstrates a basic socket connection waiting setup that you can modify and expand upon based on your specific requirements.

By understanding and implementing socket connection waiting in Python, you can develop powerful network applications that can communicate with clients over a network.