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.


2018-05-12 10:56:17 AM

Python Server

This server opens its service at port 9999 and listens and connects to an incoming tcp stream. Once a connection is established, it sends the client “Hello World” as a confirmation of connection. It then listens to what the client has to say and closes as soon as the client closes closes the connection.

#file name -> (sorry I am not that creative!)
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 simultaneously)

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**

Python Client

The following code generates a client service which tells the server above “You better call becky with the good hair” once it recieves a response from m the server. After which, it closes the connection.

#file name-> (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

Watch the video below!!