Search code examples
python-3.6python-socketio

why do I see TypeError for python socket module?


I am learning python, and these days I am trying to work with socket module. Below is the client side logic.

import socket
from threading import Thread
import ipaddress


lic_server_host = input("Please enter the hostname: ")
port = input("Please enter the License service port number: ")
client_socket = socket.socket()
client_socket.connect((lic_server_host, port))


def receive_data():
    while True:
        data = client_socket.recv(1000)
        print(data.decode())


def sending_data():
    while True:
        user_input = input()
        client_socket.sendall(user_input.encode())


t = Thread(target=receive_data)
t.start()
sending_data()

Here I am taking user's input as a hostname. However. The above porgram is not able to convert the hostname to integer. I am getting below error

client_socket.connect((lic_server_hostname, port))
TypeError: an integer is required (got type str)

I tried to use some python way to get rid of the issue by introducing for loop on the user's input as below

lic_server_host = input("Please enter the License server hostname: ")
for info in lic_server_hostname:
    if info.strip():
        n = int(info)
port = input("Please enter the License service port number: ")
client_socket = socket.socket()
client_socket.connect((n, port))

But now I get below error:

client_socket.connect((n, port))
TypeError: str, bytes or bytearray expected, not int

So based on the error I used str() function on "n". But when I do that I get below error:

n = int(info)
ValueError: invalid literal for int() with base 10: 'l'

I have also searched for the above error available on the internet but the solutions not helping me.

Please help me understand my mistake.

Thank you


Solution

  • input returns a string when connect requires port as int.

    client_socket.connect((lic_server_host, int(port)))