Reputation: 63
I am writing a simple client server program using Sockets in python. In my example, 1st I want to send a simple "text" in a packet for example, 2nd I will send an image for example.
In the client I want that if I receive a text, I print it on my console. But, if I receive a file (like an image), I save it on my hard drive.
How can I differentiate between the packets I receive on the client side?
#Server Code
import socket
host = socket.gethostname()
s_client=socket.socket()
port_server = 8081
s_client.bind((host, port_server))
s_client.listen(1)
print("Waiting for any incoming connections from clients ...")
conn_client, addr_client = s_client.accept()
#Send a text
conn_client.send("text".encode())
#Send a file (image for example)
f = open("image", "rb")
l = f.read(1024)
while (l):
conn_client.send(l)
l = f.read(1024)
#Client code
import socket
s = socket.socket()
host = socket.gethostname()
port_server = 8081
s.connect((host, port_server))
print("Connected...")
while True:
data = s.recv(1024)
#I WANT TO DIFFERENTIATE HERE
if data:
print(data)
Upvotes: 0
Views: 590
Reputation: 2803
Python's socket object is designed for low-level network communication. In other words, you can use it to send some raw data from one communication endpoint to another one. The socket object itself does not have any means to differentiate between data types or content. This typically takes place on a higher protocol layer.
For example, when a browser receives some data from a server via http, usually the content type is transmitted so the browser knows how to handle the data.
For your purpose, it might be perfectly sufficient if the server would in a similar way send some kind of prefix before the actual data - for example the string 'TXT'
if the subsequent data is a text, and 'IMG'
if the subsequent data is an image. The client could then evaluate these first three characters and interpret the data appropriately.
Upvotes: 1