Enhancing Data Serialization for Communication
In this step, we will enhance the communication between the client and server by serializing and deserializing data for transmission.
- Modify the
server.py
code to include data serialization and deserialization.
## server.py
import socket
import pickle
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind(('127.0.0.1', 8888))
server_socket.listen(1)
connection, address = server_socket.accept()
with connection:
print('Connected by', address)
while True:
data = connection.recv(1024)
if not data:
break
deserialized_data = pickle.loads(data)
processed_data = deserialized_data.upper()
connection.sendall(processed_data.encode())
- Modify the
client.py
code to include data serialization and deserialization.
## client.py
import socket
import pickle
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client_socket.connect(('127.0.0.1', 8888))
data_to_send = pickle.dumps('Hello, server')
client_socket.sendall(data_to_send)
received_data = client_socket.recv(1024)
print('Received', received_data.decode())
Run these two files at the same time and click "Split Terminal" to achieve it. The information below should be displayed on your terminal:
labex:project/ $ python server.py
Connected by ('127.0.0.1', 40082)
labex:project/ $ python client.py
Received HELLO, SERVER