I am more into web development but out of boredom decided to dabble into networking… okay let’s see what I have learned so far.
2018-05-12 10:56:17 AM
#file name -> s.py (sorry I am not that creative!)
target_host = "localhost"
target_port = 9999
#create server socket
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
#since it is a server, you will have to listen..but first bind the socket to a port
server.listen(1) #argument->backlog of connections (number of clients the server can listen to simutaneously)
connection, addr = server.accept() #when a client connects to this "socket -> localhost:9999", the server accepts the client and establishes a connection
#what can I do with the newly created connection ? probably wait for the client to send something first or the other way around
connection.send("Hello World".encode()) # so in this case, the server sends first;#encode converts the string to bytes which are sent over the connection to the server
response, addr= connection.recvfrom(4096) # the server is now waiting for a response from the client; 4096 –> maximum byte length of data correct me if I am wrong
print(response.decode()) #the response is sent in bytes, so we need to decode (convert to a str type) before we pass it the the print function
connection.close() #already! but we just met…. **sad face**
Now unto the Client –> the dude that connects first
#file name-> c.py (yep… just role with it)
remote_host = "localhost"
remote_port = 9999
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM) #creates a socket
#let’s connect to a server / or another socket
#since our server first sent data upon accepted connection, our client will first listen for a response and then send something
response = client.recv(4096)
#send something back to the server
client.send("You better call becky with the good hair!".encode())
print(response.decode()) #similar to the server’s case
client.close() #disable socket
Watch the video below!!