Skip to content

Commit

Permalink
Create communication.py
Browse files Browse the repository at this point in the history
  • Loading branch information
KOSASIH authored May 10, 2024
1 parent 2be8c78 commit e65ed48
Showing 1 changed file with 51 additions and 0 deletions.
51 changes: 51 additions & 0 deletions network/communication.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
import json
import requests
import websockets

def send_http_request(url, method, headers=None, data=None):
"""
Sends an HTTP request to the specified URL using the specified method, headers, and data.
"""
if headers is None:
headers = {}

if method == "GET":
response = requests.get(url, headers=headers, data=data)
elif method == "POST":
response = requests.post(url, headers=headers, data=json.dumps(data))
elif method == "PUT":
response = requests.put(url, headers=headers, data=json.dumps(data))
elif method == "DELETE":
response = requests.delete(url, headers=headers, data=data)
else:
raise ValueError("Invalid HTTP method")

if response.status_code != 200:
raise Exception("HTTP request failed with status code {}".format(response.status_code))

return response.json()

def send_websocket_message(websocket, message):
"""
Sends a message over a WebSocket connection.
"""
websocket.send(json.dumps(message))

def receive_websocket_message(websocket):
"""
Receives a message over a WebSocket connection.
"""
return json.loads(websocket.recv())

def create_websocket_connection(url):
"""
Creates a new WebSocket connection to the specified URL.
"""
websocket = websockets.connect(url)
return websocket

def close_websocket_connection(websocket):
"""
Closes the specified WebSocket connection.
"""
websocket.close()

0 comments on commit e65ed48

Please sign in to comment.