Skip to content

Instantly share code, notes, and snippets.

@abduakhatov
Created January 7, 2023 17:57
Show Gist options
  • Save abduakhatov/0b551ce4cc3baa4179d7bd310029e24a to your computer and use it in GitHub Desktop.
Save abduakhatov/0b551ce4cc3baa4179d7bd310029e24a to your computer and use it in GitHub Desktop.

Revisions

  1. abduakhatov created this gist Jan 7, 2023.
    16 changes: 16 additions & 0 deletions client.py
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,16 @@
    # client.py
    import socket

    def main():
    # creating the socket
    sck = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    # just connecting
    sck.connect(("localhost", 7456))

    print("Sending data...")
    sck.sendall(b"Hola server, are you bored?")
    # I don't care about your response server, I'm closing
    sck.close()

    if __name__ == "__main__":
    main()
    36 changes: 36 additions & 0 deletions server.py
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,36 @@
    # server.py
    import socket

    def main():
    # creating the socket
    sck = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

    # binding the socket to the port 7456
    # notice that bind() take a tuple as argument
    sck.bind(('localhost', 7456))

    # now is time to say, I'm ready for connection OS, could you let me please?
    # the 1 specified how many connection it will queue up, until
    # start rejecting attempts of connections.
    sck.listen(1)

    print("Hey you I'm listening on 7456...weird port by the way")

    # accepting the incoming connection
    (client_sock, address) = sck.accept()
    while True:
    # 1024 is a magic number used on every networking tutorial out there
    # so here I also make use of it. Also in this case means that the socket
    # will process up to 1024 bytes of the incoming message from the client
    msg = client_sock.recv(1024)
    if not msg:
    break
    print(f"FROM: {address} MSG: {msg}")
    print()

    # good bye socket
    client_sock.close()


    if __name__ == "__main__":
    main()