rob
rob

Reputation: 1

Getting ust be string or buffer not int Error in my program

I am new to python program. And I written a client/server program for adding two numbers. Client give two numbers and server adds up. While running, I am hitting with the above error on the client side.

Client.py

!/usr/bin/python

import socket
import sys

sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_address = ('127.0.0.1', 58817)
sock.connect(server_address)

a=raw_input("Enter a number: ")
b=raw_input("Enter a number: ")

sock.sendall(a,b)
data = sock.recv(1024)

print data

sock.close()

Server.py

!/usr/bin/python

import socket
import sys

def sum(a, b):
  data=a + b
  return data

sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_address = ('127.0.01', 58817)
sock.bind(server_address)
sock.listen(1)
connection, client_address = sock.accept()

print ("connection from", client_address)

while True:
 data=connection.recv(1024)
 if not data: break
 print "server received : ", repr(data)
 sum(data)

connection.sendall(data)
connection.close()

while running the program, i am hitting with below error in client side

Enter a number: 4
Enter a number: 3

Traceback (most recent call last):



File "clientadd.py", line 15, in <module>
    sock.sendall(a,b)
  File "/usr/lib/python2.7/socket.py", line 224, in meth
    return getattr(self._sock,name)(*args)
TypeError: an integer is required

There is some mistake with client side assigning int (a,b). How to change that one and put in some order as read by server ? Can anyone help me on this ? and can check if the program is good and in working condition to get output ?

Thanks!

Upvotes: 0

Views: 70

Answers (2)

Shihab Shahriar Khan
Shihab Shahriar Khan

Reputation: 5455

Remember, you can only send or receive bytes over socket. So, both your client and socket needs to reflect that.

On client side, instead of sendall(a,b), you can:

b=bytes("{},{}".format(a,b),"ascii")
sock.sendall(b)

On server side, parse the string to get integers.

data=connection.recv(1024)
a,b = data.decode().split(',')
a,b = int(a),int(b)

You should be able to send back the sum as bytes now.

Upvotes: 1

jath03
jath03

Reputation: 2359

You're server_address on the server side has a typo. It should be ('127.0.0.1', 58817) the client will give an error, because the server it is trying to connect to doesn't exist.

Upvotes: 0

Related Questions