omega_elite
Posts: 1
Joined: Wed Jun 10, 2020 9:44 pm

ValueError: invalid literal for int() with base 10: 'test'

Wed Jun 10, 2020 9:50 pm

Hi

I am getting the error below when running the following code and i send data "test" from realterm on a windows PC to the server using code below and and dont know why ???

Code: Select all

import socket 
import threading


PORT = 5050
SERVER = socket.gethostbyname(socket.gethostname())
ADDR = (SERVER, PORT)

DISCONNECT_MESSAGE = "!DISCONNECT"

server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind(ADDR)

def handle_client(conn, addr):
    print(f"[NEW CONNECTION] {addr} connected.")

    connected = True
    while connected:
            message = conn.recv(1024)
            print(message.decode('ascii'))
            conn.send("Msg received")

    conn.close()
        

def start():
    server.listen()
    print(f"[LISTENING] Server is listening on {SERVER}")
    while True:
        conn, addr = server.accept()
        thread = threading.Thread(target=handle_client, args=(conn, addr))
        thread.start()
        print(f"[ACTIVE CONNECTIONS] {threading.activeCount() - 1}")


print("[STARTING] server is starting...")
start()
Exception in thread Thread-29:
Traceback (most recent call last):
File "C:\Users\Andy\AppData\Local\Programs\Python\Python38-32\lib\threading.py", line 932, in _bootstrap_inner
self.run()
File "C:\Users\Andy\AppData\Local\Programs\Python\Python38-32\lib\threading.py", line 870, in run
self._target(*self._args, **self._kwargs)
File "c:/Python Code/server test.py", line 21, in handle_client
print(message.decode('ascii'))
ValueError: invalid literal for int() with base 10: 'test'

ghp
Posts: 1592
Joined: Wed Jun 12, 2013 12:41 pm
Location: Stuttgart Germany
Contact: Website

Re: ValueError: invalid literal for int() with base 10: 'test'

Thu Jun 11, 2020 4:53 am

When I run this code with python3, the error message received is:

Code: Select all

Exception in thread Thread-1:
Traceback (most recent call last):
  ...
  File "... src/test.py", line 21, in handle_client
    conn.send("Msg received")
TypeError: a bytes-like object is required, not 'str'
which is caused by the line "conn.send("Msg received")", should be "conn.send( b"Msg received")".

Looks as if the error message "ValueError: invalid literal for int() with base 10: 'test'" is not caused by this code snippet.

When I try to convert the received data to an int, like:
print(int(message.decode('ascii'))),
then the same error message is thrown when input is e.g. "hello", sent by remote client.

pfletch101
Posts: 630
Joined: Sat Feb 24, 2018 4:09 am
Location: Buffalo, NY, USA

Re: ValueError: invalid literal for int() with base 10: 'test'

Thu Jun 11, 2020 9:59 pm

I think that you need to look up the syntax for message.decode(). It looks to me as if Python is (not unreasonably) telling you that it can't convert an alpha string into an int.

Return to “Python”