为什么这不能将我连接到我的服务器?

我正在尝试建立与 server.py 的连接,但 client.py 输出此错误


Traceback (most recent call last):

  File "C:\Users\Nathan\Desktop\Coding\Langs\Python\Projects\Chatting Program\Client.py", line 15, in <module>

    clientsocket.connect((host, port)) # Connects to the server

TypeError: an integer is required (got type str)

这是我的代码...


## CLIENT.PY

from socket import *

import socket


host = input("Host: ")

port = input("Port: ")

#int(port)


username = input("Username: ")

username = "<" + username + ">"

print(f"Connecting under nick \"{username}\"")


clientsocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # Creates socket

clientsocket.connect((host, port)) # Connects to the server


while True:

    Csend = input("<MSG> ") # Input message

    Csend = f"{username} {Csend}" # Add username to message

    clientsocket.send(Csend) # Send message to ONLY the server

如果我的 server.py 有问题,那么这是代码


## SERVER.PY

from socket import *

import socket

import select


host_name = socket.gethostname()


HOST = socket.gethostbyname(host_name) 

PORT = 12345


print(f"Server Info\nHOST: {HOST}\nPORT: {PORT}")


serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

serversocket.bind((HOST, PORT))

serversocket.listen(5)

clientsocket, address = serversocket.accept()


print(address)

with clientsocket:

    while True:

        Srecv = clientsocket.recv(1024)

        print(f"{username} - {address}: {Srecv}")

        # Add server time to message before sending

        clientsocket.sendall(Srecv)

我尝试过将主机和端口转换为str,int和浮点数,但它只能成功转换为str。任何帮助将不胜感激。提前致谢!


陪伴而非守候
浏览 146回答 2
2回答

蝴蝶不菲

编译错误是相当公平的:input()&nbsp;返回端口号的字符串,而您的函数需要一个整数。您可以通过将端口转换为整数来解决此问题 - 您的注释很接近:端口 = int(port)。

开满天机

如果你看一下 python 文档,input() 总是返回一个字符串。传递给客户端ocket.connect() 的元组中的第二个值必须是一个整数,但是,您正在传递一个字符串值。您必须首先使用下面的代码转换您的端口:port = int(port).#ORport = int(input("Port: "))始终检查文档!
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python