我正在尝试制作一个基本的python网络程序。我要做的就是在服务器和客户端之间来回发送文本字符串。我试图在Raspberry Pi上托管服务器,并与Windows 10上的客户端连接。该程序在我的计算机上本地运行良好,但是当我尝试连接到服务器时,它给了我ConnectionRefusedError: [WinError 10061] No connection could be made because the target machine actively refused it.
我的服务器代码如下:
import socket # Import socket module
import netifaces as ni
s = socket.socket() # Create a socket object
host = socket.gethostname() # Get local machine name
port = 12345 # Reserve a port for your service.
s.bind((host, port))
#host_ip = ni.ifaddresses('wlan0')[ni.AF_INET][0]['addr']
host_ip = "bruh?"
print("Server started! \nHostname: " + host + " \nIP: " + host_ip + " \nPort: " + str(port))
s.listen() # Now wait for client connection.
while True:
c, addr = s.accept() # Establish connection with client.
print('Got connection from', addr)
output = "Welcome to the server!".encode()
c.send(output)
c.close()
客户代码:
import socket
s = socket.socket()
host = 192.168.1.21
port = 12345
s.connect((host, int(port)))
noResponse = False
serverResponse = s.recv(1024).decode()
print(serverResponse)
s.close()
有人知道我的问题是什么吗?谢谢。
您可能由于某些原因而收到ConnectionRefusedError,请尝试以下操作:
另外,我将代码更改如下:
服务器:
import socket
HOST = '' # localhost
PORT = # IMPORTANT !! Do not use reserved ports
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
sock.bind((HOST, PORT))
sock.listen()
conn, addr = sock.accept()
with conn:
print('Connected by', addr)
while True:
data = conn.recv(1024)
if not data:
break
print('Data: ',data)
conn.sendall('RT')
客户:
import socket
HOST = '' # server IP address
PORT = # server port
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
sock.connect((HOST, PORT))
sock.sendall('Hello, I am the Client')
data = sock.recv(1024)
print('Received', data)
这样,您正在使用TCP连接,并且可以使用其他TCP服务器和客户端仿真器来测试代码。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句