How to send multiple integer values using s.send in python

0 votes
asked Sep 12, 2017 by amish-gupta

I have a client and a server. I am sending two integer values to server using s.send one after another.But my program gets stuck on server and not moves on. Here is my client code.

import socket
s=socket.socket()
host=socket.gethostname()
port=8080
print("RSA Client Side \n")
p=int(input("Enter p(prime number) "))

q=int(input("Enter q(prime number) "))
n=p*q
print("First part of public key is %d"%n)
a=(p-1)*(q-1)
print("Euler Totient function is %d\n"%a)
e=int(input("Enter exponent e value such that 1<e<TF and is coprime "))
print("Public key is n=%d , e=%d\n"%(n,e))
s.connect((host, port))
s.send(str.encode(str(n)))
s.send(str.encode(str(e)))
m=int((s.recv(2048)).decode('utf-8'))
print("Recieved encrypted message is %d"%m)
s.close

and server code

 import socket
s=socket.socket()
host=socket.gethostname()
port=8080
s.bind((host,port))
s.listen(5)
while 1:
    c,address=s.accept()
    n=int((c.recv(2048)).decode('utf-8'))
    e=int((c.recv(2048)).decode('utf-8'))
    print("Recieved public key from client is n=%d,e=%d\n"%(n,e))
    m=input("enter your message ")
    if m.isdigit():
        c=(m**e)%n
    print("Encrypted data send is %d\n"%m)
    c.send(str.encode(str(m)))
s.close

2 Answers

0 votes
answered Sep 12, 2017 by jim-fasarakis-hillia

You have received all available data sent with n=int((c.recv(2048)).decode('utf-8')); the consequenct c.recv() call blocks waiting for data.

Send both numbers together separated by a delimiter and split on that on the server side:

On the client:

s.sendall(str.encode("\n".join([str(n), str(e)])))

while on the server:

n, e = [int(i) for i in c.recv(2048).decode('utf-8').split('\n')]

in addition to that, you currently aren't closing the socket, you'll need to use s.close().

0 votes
answered Sep 12, 2017 by jasonharper

The first time you called recv(2048), you most likely received both the n and e values run together - stream protocols like TCP do not preserve the boundaries between individual calls to .send(). To send multiple values over a stream, YOU are entirely responsible for separating them at the receiving end. Common strategies are to send data that is of a fixed length (and .recv() only that amount of data), or to separate them with a delimiter such as a newline character.

Welcome to Q&A, where you can ask questions and receive answers from other members of the community.
Website Online Counter

...