我根据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机器?
答案 0 :(得分:2)
在您的服务器代码中:
server_address = ('localhost', 15000)
这在ipnumer 127.0.0.1上设置了一个监听器。这个&#39; localhost&#39;无法从此服务器外部的客户端联系ip。
如果您希望服务器收听所有已分配的IP地址,请使用:
server_address = ('0.0.0.0', 15000)
答案 1 :(得分:1)
当您创建一个绑定到localhost
地址的套接字时,您将创建一个侦听&#34; loopback接口&#34;的套接字,即127.0.0.1。您似乎尝试通过本地IP-192.168.18.250连接到服务器,该IP-192.168.18.250分配给不同的接口(通常是连接到LAN的接口)。因为在该接口上没有任何东西正在侦听端口15000,所以会拒绝连接。
这里有两个解决方案:要么将服务器更改为正在监听正确的接口(听0.0.0.0一般在这里工作,尽管如果它保证静态IP,请改用它)或更改客户端尝试连接到loopback接口 - 尝试连接127.0.0.1或&#34; localhost&#34;