[파이썬] requests 웹소켓과의 통신

In modern web development, WebSocket has gained popularity for enabling real-time, bi-directional communication between a client and a server. It is an alternative to traditional HTTP communication, providing a more efficient and continuous connection.

In this tutorial, we will explore how to establish a WebSocket connection using Python’s Requests library, giving you the ability to incorporate WebSocket communication in your Python applications.

Prerequisites

To follow along with this tutorial, you will need:

  1. Python installed on your machine (version 3.6 or higher)
  2. The Requests library installed (pip install requests)

Establishing a WebSocket Connection

  1. Start by importing the necessary libraries:
import requests
from websocket import create_connection
  1. Define the URL of the WebSocket server you want to connect to:
ws_url = "wss://your-websocket-server.com"
  1. Next, create a GET request to initiate the WebSocket connection:
response = requests.get(ws_url)
  1. Retrieve the WebSocket URL from the response headers:
websocket_url = response.headers.get('webSocketLocation')
  1. Finally, use the create_connection function from websocket library to establish the WebSocket connection:
ws = create_connection(websocket_url)

Sending and Receiving WebSocket Messages

Congratulations! You have successfully established a WebSocket connection. Now let’s learn how to send and receive messages.

Sending Messages

To send a message to the server, use the send method of the WebSocket object:

message = "Hello, server!"
ws.send(message)

Receiving Messages

To receive messages from the server, use the recv method of the WebSocket object:

while True:
    received_message = ws.recv()
    print("Received message:", received_message)

Disconnecting from the WebSocket Server

To gracefully close the WebSocket connection, use the close method:

ws.close()

Conclusion

In this tutorial, you learned how to establish a WebSocket connection in Python using the Requests library. You also learned how to send and receive messages over the WebSocket connection. WebSocket enables real-time communication, making it a valuable tool in building interactive and responsive web applications.

Remember to check the documentation of the WebSocket server you’re connecting to for specific message formats and functionalities. Happy coding!