为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

陪伴而非守候 2022-09-13 19:40:41
我正在尝试建立与 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 serverTypeError: an integer is required (got type str)这是我的代码...## CLIENT.PYfrom socket import *import sockethost = 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 socketclientsocket.connect((host, port)) # Connects to the serverwhile 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.PYfrom socket import *import socketimport selecthost_name = socket.gethostname()HOST = socket.gethostbyname(host_name) PORT = 12345print(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。任何帮助将不胜感激。提前致谢!
查看完整描述

2 回答

?
蝴蝶不菲

TA贡献1810条经验 获得超4个赞

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

端口 = int(port)。


查看完整回答
反对 回复 2022-09-13
?
开满天机

TA贡献1786条经验 获得超13个赞

如果你看一下 python 文档,input() 总是返回一个字符串。传递给客户端ocket.connect() 的元组中的第二个值必须是一个整数,但是,您正在传递一个字符串值。您必须首先使用下面的代码转换您的端口:


port = int(port).


#OR


port = int(input("Port: "))

始终检查文档!


查看完整回答
反对 回复 2022-09-13
  • 2 回答
  • 0 关注
  • 145 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号