[Python] Python TCP sockets headers

Discussão em 'Python' iniciado por Stack, Novembro 30, 2024.

  1. Stack

    Stack Membro Participativo

    I need to create a communication between a client and a server with TCP. But I'd like to send and work with "headers". So from the client I'd like to send a header "COMMAND1" and the server returns me something.

    I have the following code:

    Server

    import socket
    import threading

    bind_ip = '0.0.0.0'
    bind_port = 9998

    server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    server.bind((bind_ip, bind_port))
    server.listen(5) # max backlog of connections

    print ('Listening on {}:{}'.format(bind_ip, bind_port))


    def handle_client_connection(client_socket):
    request = client_socket.recv(1024)
    print ('Received {}'.format(request))
    client_socket.send('Response1!'.encode('utf-8'))
    client_socket.close()

    while True:
    client_sock, address = server.accept()
    print ('Accepted connection from {}:{}'.format(address[0], address[1]))
    client_handler = threading.Thread(
    target=handle_client_connection,
    args=(client_sock,) # without comma you'd get a... TypeError: handle_client_connection() argument after * must be a sequence, not _socketobject
    )
    client_handler.start()


    Client

    import socket

    hostname, sld, tld, port = 'www', 'integralist', 'co.uk', 80
    target = '{}.{}.{}'.format(hostname, sld, tld)

    # create an ipv4 (AF_INET) socket object using the tcp protocol (SOCK_STREAM)
    client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

    # connect the client
    # client.connect((target, port))
    client.connect(('0.0.0.0', 9998))

    # send some data (in this case a HTTP GET request)
    client.send('hi'.encode('utf-8'))

    # receive the response data (4096 is recommended buffer size)
    response = client.recv(4096)

    print (response)


    Anyone knows the best way to return "Response1!" when the header is "COMMAND1" and "Response2!" when the header is "COMMAND2"?

    I can't find examples on how to use headers

    EDIT: It doesn't have to be "COMMAND1" or "COMMAND2" it can be a "0" or "1", or anything else.

    Continue reading...

Compartilhe esta Página