我正在学习python,这些天我正在尝试使用套接字模块。下面是客户端逻辑。
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()
在这里,我将用户的输入作为主机名。然而。上面的 porgram 无法将主机名转换为整数。我得到以下错误
client_socket.connect((lic_server_hostname, port))
TypeError: an integer is required (got type str)
我试图使用一些python方法来摆脱这个问题,通过在用户的输入上引入for循环,如下所示
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))
但是现在我得到以下错误:
client_socket.connect((n, port))
TypeError: str, bytes or bytearray expected, not int
因此,基于错误,我在"n"上使用了str((函数。但是当我这样做时,我得到以下错误:
n = int(info)
ValueError: invalid literal for int() with base 10: 'l'
我还搜索了互联网上可用的上述错误,但解决方案对我没有帮助。
请帮助我理解我的错误。
谢谢
input
当需要端口作为int
时connect
返回一个字符串。
client_socket.connect((lic_server_host, int(port)))