C_socket_api/main.py

37 lines
727 B
Python
Raw Permalink Normal View History

2025-02-07 08:00:59 +00:00
import socket
HOST = '127.0.0.1'
PORT = 8080
BUFFER_SIZE = 1024
def send_command(command):
# Create a socket object
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
# Connect to the server
client_socket.connect((HOST, PORT))
# Send the command
client_socket.sendall(command.encode('utf-8'))
# Receive the response
response = client_socket.recv(BUFFER_SIZE).decode('utf-8')
# Close the socket
client_socket.close()
return response
except Exception as e:
print(f"An error occurred: {e}")
def main():
print('Sended: ping')
print(f'Received: {send_command("ping")}')
print('Sended: hello')
print(f'Received: {send_command("hello")}')
if __name__ == "__main__":
main()