亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

為什么這不能將我連接到我的服務器?

為什么這不能將我連接到我的服務器?

陪伴而非守候 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 關注
  • 128 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號