user3312583
user3312583

Reputation: 33

Python How to distinguish data in python socket module(when server receive.)

I don't know how to distinguish data which received in server.

I want to distinguish the data by setting MessageID(example name) when I send data or receive data.

Here's the example.:

server

import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host=''
port=int(input(Please Enter the port:))
s.bind((host,port))
s.listen(1)
conn, addr = s.accept()
print('Someone connected.He :%s'%addr)
while True:
    data=conn.recv(1024,MessageID) # I want to make this.
    print(data)

client

import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host=''
port=int(input(Please Enter the port:))
s.connect((host,port))
data='hello world'
data=data.encode('utf-8') # I encoded data because Python 3.3.3's socket module doesn't
work with string(str) when I send data.
s.send(data,MessageID) # This is what I want.I want to set messageID which can        distinguish data.

How to make like this?

How other programmers distinguish data in python..?

I really want is : Don't receive if not messageID which server want.

Upvotes: 1

Views: 1483

Answers (1)

msvalkon
msvalkon

Reputation: 12077

You will need to put the MessageID into the data you're sending. It might be a good idea to use some known protocol for the data, so you know what to expect, but here's a naive example. You will need to implement proper error handling. Note that you will also have to implement a loop to read all of the data, as reading the socket with a single recv will eventually lead to a situation where you're receiving partial messages. I don't really know what your data is so I won't make a guess about it.

The client

....
message_id = 1
data = '{}:hello world!'.format(message_id)
data = data.encode('utf-8')
s.send(data)

The server

while True:
    data = conn.recv(1024)
    if not data:
       # Always handle the case where the client
       # connects but sends no data. This means the socket is closed
       # by the other end.
       break
    message_id, message = data.split(":", 1)
    print "Got message, id: {}, data: {}".format(message_id, message)

If you'd implement this using pickle or json you could simply use dictionaries:

# Client
data = {'message_id': 1, 'message': 'hello world'}
data = pickle.dumps(data) # Or json.dumps(data)
s.send(data)

# Server
while True:
    data = conn.recv(1024)
    if not data:
        break
    data = pickle.loads(data) # Or json.loads(data)
    print "Got id: {message_id}, data: {message}".format(**data)

Upvotes: 2

Related Questions