NAOR OR ZION
NAOR OR ZION

Reputation: 31

Python sockets error TypeError: a bytes-like object is required, not 'int'

I am trying to create a server that will recieve messages from the client and answer them properly. When i ask for a random number(RAND) i get this error "a bytes-like object is required, not 'int'", how can i fix it?

and another question, i tried to change the bytes in 'recv' function, and didn't succeed. Can somebody help me out ):?

import socket
import time
import random

server_socket = socket.socket()
server_socket.bind(('0.0.0.0', 8820))
server_socket.listen(1)
(client_socket, client_address) = server_socket.accept()
localtime = time.asctime( time.localtime(time.time()) )
ran = random.randint(0,10)
RUN = True
recieve = 1024

while RUN:
    client_input = (client_socket.recv(recieve)).decode('utf8')
    print(client_input)
    if client_input == 'TIME':
        client_socket.send(localtime.encode())
    elif client_input == 'RECV':
        recieve = client_socket.send(input("the current recieve amount is " + int(recieve) + ". Enter the recieve amount: "))
    elif client_input == 'NAME':
        client_socket.send(str("my name is SERVER").encode())
    elif client_input == 'RAND':
        client_socket.send(ran.encode())
    elif client_input == 'EXIT':
        RUN = False
    else:
        client_socket.send(str("I can only get 'TIME', 'NAME', 'RAND', 'EXIT'").encode())
client_socket.close()
server_socket.close()

Upvotes: 0

Views: 495

Answers (2)

jerry denis inyang
jerry denis inyang

Reputation: 21

The reason for this error is that in Python 3, strings are Unicode, but when transmitting on the network, the data needs to be bytes instead. So... a couple of suggestions:

Suggest using client_socket.sendall() instead of client_socket.send() to prevent possible issues where you may not have sent the entire msg with one call (see docs). For literals, add a 'b' for bytes string: client_socket.sendallsend(str("I can only get 'TIME', 'NAME', 'RAND', 'EXIT'").encode()) For variables, you need to encode Unicode strings to byte strings (see below)

    output = 'connection has been processed'
client_socket.sendall(output.encode('utf-8'))

Upvotes: 1

NAOR OR ZION
NAOR OR ZION

Reputation: 31

the client code is:

import socket

my_socket = socket.socket()
my_socket.connect(('127.0.0.1', 8820))
while True:
    user_input = input("Naor: ")
    my_socket.send(user_input.encode())
    data = my_socket.recv(1024)
    print("Server: " + data.decode('utf8'))
my_socket.close()

Upvotes: 1

Related Questions