Python Networking | Super Beginner Series | Simple Server and Client – “Hello World”

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.

Networking 

2018-05-12 10:56:17 AM


[sourcecode lang=”python”]
#file name -> s.py (sorry I am not that creative!)
#server
import socket

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.bind((target_host, target_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**

 
<pre><pre>[/sourcecode]

Now unto the Client –> the dude that connects first

[sourcecode lang=”python”]</pre>
</pre>
#file name-> c.py (yep… just role with it)
import socket

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
client.connect((remote_host, remote_port))

#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

&nbsp;
<pre><pre>[/sourcecode]

Watch the video below!!