![](/img/trans.png)
[英]ConnectionRefusedError: [Errno 61] Connection refused Python3.8.5 on Mac
[英]Python ConnectionRefusedError: [Errno 61] Connection refused
我見過類似的問題,但我無法修復此錯誤。 我和我的朋友正在制作一個聊天程序,但我們不斷收到錯誤 ConnectionRefusedError: [Errno 61] Connection refused We are on different.networks by the way。 這是我的服務器代碼
import socket
def socket_create():
try:
global host
global port
global s
host = ''
port = 9999
s = socket.socket()
except socket.error as msg:
print("Socket creation error" + str(msg))
#Wait for client, Connect socket and port
def socket_bind():
try:
global host
global port
global s
print("Binding socket to port: " + str(port))
s.bind((host, port))
s.listen(5)
except socket.error as msg:
print("Socket binding error" + str(msg) + "\n" + "Retrying...")
socket_bind
#Accept connections (Establishes connection with client) socket has to be listining
def socket_accept():
conn, address = s.accept()
print("Connection is established |" + " IP:" + str(address[0]) + "| port:" + str(address[1]))
chat_send(conn)
def chat_send(conn):
while True:
chat =input()
if len(str.encode(chat)) > 0:
conn.send(str.encode(chat))
client_response = str(conn.recv(1024), "utf-8")
print(client_response)
def main():
socket_create()
socket_bind()
socket_accept()
main()
還有我的客戶代碼
import socket
#connects to server
s = socket.socket()
host = '127.0.0.1'
port = 9999
s.connect((host, port))
#gets chat
while True:
data = s.recv(1024)
print (data[:].decode("utf-8"))
chat = input()
s.send(str.encode(chat))
這可能無法回答您原來的問題,但我遇到了這個錯誤,這只是因為我沒有先啟動服務器進程來監聽我選擇測試的端口上的 localhost (127.0.0.1)。 為了讓客戶端連接到本地主機,服務器必須監聽本地主機。
'127.0.0.1'
表示本地計算機 - 因此客戶端與同一台計算機上的服務器一致。 客戶端必須使用來自服務器的IP
- 如192.168.0.1
。
在服務器上檢查:
在 Windows 上(在cmd.exe
)
ipconfig
在 Linux 上(在控制台中)
ifconfig
但是如果你在不同的網絡中,那么它可能不起作用。 ipconfig/ifconfig
返回僅在本地網絡中可見的本地 IP(如192.168.0.1
)。 然后,您可能需要在您的路由器和提供商路由器上設置外部 IP 和設置(重定向)。 外部IP
可以是您的路由器或提供商路由器的 IP。 當您訪問像http://httpbin.org/ip這樣的頁面時,您可以看到您的外部 IP。 但它仍然需要一些工作,否則它會成為更大的問題。
您只需首先啟動服務器,然后運行 client_code。 在 VS Code 中,我打開了 2 個終端。 一個用於 server_code 運行While True
,另一個用於 client_code
所以這可能不會具體解決你的問題,但它解決了我的問題,它可以幫助我使用 vscode 的其他人,我使用一些運行我的代碼的擴展,所以當你想運行你的服務器時,在你的 CMD 或終端上運行它並運行你的客戶端在 vscode 中它幫助了我(也許重要的是我在 mac 上工作所以可能是特定的操作系統問題)
如果您正在連接到一個開放的主機:端口但沒有綁定到它的服務,您可能會看到這個 IIRC。 例如,對於 ssh,您有時會在嘗試連接到正在啟動但 sshd 未運行的服務器時看到此信息。
此代碼不適用於聊天,您必須使用解鎖套接字並選擇模塊或其他異步模塊
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.