![](/img/trans.png)
[英]Errno 61: Connection refused error when trying to connect to python server
[英]Getting connection refused when trying to connect to a tcp server with python
我根據python套接字指南編寫了兩個程序。 我正在使用rasbperry pi 3作為客戶端,並使用常規的Linux ubuntu計算機作為服務器。 這是服務器軟件:
import socket
import sys
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_address = ('localhost', 15000)
print("starting up on %s port %s" % server_address, file=sys.stderr)
sock.bind(server_address)
# Listen for incoming connections
sock.listen(1)
while True:
# Wait for a connection
print("waiting for a connection", file=sys.stderr)
connection, client_address = sock.accept()
try:
print("connection from ", client_address, file=sys.stderr)
# Receive the data in small chunks and retransmit it
while True:
data = connection.recv(16)
print("received %s" % data, file=sys.stderr)
if data:
print("sending data back to the client", file=sys.stderr)
connection.sendall(data)
else:
print("no more data from ", client_address, file=sys.stderr)
break
finally:
# Clean up the connection
connection.close()
這是客戶端軟件:
import socket
import sys
# Create a TCP/IP socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# Connect the socket to the port where the server is listening
server_address = ('192.168.18.250', 15000)
print("connecting to %s port %s" % server_address, file=sys.stderr)
sock.connect(server_address)
try:
# Send data
message = "This is the message. It will be repeated."
print("sending %s" % message, file=sys.stderr)
sock.sendall(message)
# Look for the response
amount_received = 0
amount_expected = len(message)
while amount_received < amount_expected:
data = sock.recv(16)
amount_received += len(data)
print("received %s" % data, file=sys.stderr)
finally:
print("closing socket")
sock.close()
這是服務器上的輸出:
peter@GIGAS:~/thermServer$ python3 thermServer.py
starting up on localhost port 15000
waiting for a connection
這是樹莓派的輸出:
pi@raspberrypi:~ $ python3 thermClient.py
connecting to 192.168.18.250 port 15000
Traceback (most recent call last):
File "thermClient.py", line 10, in <module>
sock.connect(server_address)
ConnectionRefusedError: [Errno 111] Connection refused
我已經在路由器中轉發了端口,但由於這是內部流量,所以不重要,我是否錯過了在服務器中添加一些可以正確打開端口的東西,還是我需要在Linux機器中擺弄項目之外的東西? ?
在服務器代碼中,您具有:
server_address = ('localhost', 15000)
這將在ipnumer 127.0.0.1上設置一個偵聽器。 無法從該服務器外部的客戶端聯系此“ localhost” IP。
如果希望服務器在所有分配的IP地址上進行偵聽,請使用:
server_address = ('0.0.0.0', 15000)
創建綁定到localhost
地址的套接字時,將創建一個偵聽“回送接口”(即127.0.0.1)的套接字。 您似乎正在嘗試通過本地IP-192.168.18.250連接到服務器,該IP已分配給另一個接口(通常是連接到LAN的接口)。 由於沒有人在該接口上監聽端口15000,因此連接被拒絕。
您在這里有兩種解決方案:要么更改服務器以偵聽正確的接口(雖然可以保證使用靜態IP,但在這里通常聽0.0.0.0即可,或者改為使用該客戶端嘗試連接到該接口)。回送接口-嘗試在127.0.0.1或“ localhost”上連接
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.