Created
January 7, 2023 17:57
-
-
Save abduakhatov/0b551ce4cc3baa4179d7bd310029e24a to your computer and use it in GitHub Desktop.
TCP handshake
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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() |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment