简体   繁体   English

Python 中 TCP 连接的简单套接字编程练习; 错误:“无法建立连接,因为目标机器主动拒绝它”

[英]simple socket programming exercise for TCP connections in Python; Error: "No connection could be made because the target machine actively refused it"

I am working on a very basic exercise designed to familiarize students with programming related to networks.我正在做一个非常基本的练习,旨在让学生熟悉与网络相关的编程。 This particular assignment is a common one as is described as follows:这个特定的任务是一个常见的任务,如下所述:

In this assignment, you will learn the basics of socket programming for TCP connections in Python: how to create a socket, bind it to a specific address and port, as well as send and receive an HTTP packet.在本作业中,您将了解 Python 中 TCP 连接的套接字编程基础知识:如何创建套接字,将其绑定到特定地址和端口,以及发送和接收 Z293C9EA246FF9985DC6F62A650ZF 数据包。 You will also learn some basics of HTTP header format.您还将学习 HTTP header 格式的一些基础知识。 You can only use Python3.您只能使用 Python3。

You will develop a web server that handles one HTTP request at a time.您将开发一个 web 服务器,一次处理一个 HTTP 请求。 Your web server should accept and parse the HTTP request, get the requested file from the server's file system, create an HTTP response message consisting of the requested file preceded by header lines, and then send the response directly to the client. Your web server should accept and parse the HTTP request, get the requested file from the server's file system, create an HTTP response message consisting of the requested file preceded by header lines, and then send the response directly to the client. If the requested file is not present in the server, the server should send an HTTP “404 Not Found” message back to the client.如果服务器中不存在请求的文件,则服务器应将 HTTP “404 Not Found”消息发送回客户端。

Part one specification:第一部分规格:

Put the attached HTML file (named HelloWorld.html) in the same directory in which the server webserver.py runs.将附加的 HTML 文件(名为 HelloWorld.html)放在运行服务器 webserver.py 的同一目录中。 Run the server program.运行服务器程序。 Determine the IP address of the host that is running the server (eg, 128.238.251.26 or localhost).确定运行服务器的主机的 IP 地址(例如,128.238.251.26 或 localhost)。 From another host, open a browser and provide the corresponding URL.从另一台主机打开浏览器并提供相应的 URL。 For example: http://128.238.251.26:6789/HelloWorld.html .例如: http://128.238.251.26:6789/HelloWorld.html You can open a browser in the same host where the server runs and use the following http://localhost:6789/HelloWorld.html.您可以在服务器运行的同一主机中打开浏览器并使用以下 http://localhost:6789/HelloWorld.html。

'HelloWorld.html' is the name of the file you placed in the server directory. 'HelloWorld.html' 是您放置在服务器目录中的文件的名称。 Note also the use of the port number after the colon.还要注意冒号后面的端口号的使用。 You need to replace this port number with the port number that was assigned to you.您需要将此端口号替换为分配给您的端口号。 In the above example, we have used port number 6789. The browser should then display the contents of HelloWorld.html.在上面的例子中,我们使用了端口号 6789。浏览器应该会显示 HelloWorld.html 的内容。 If you omit “:6789”, the browser will assume port 80 (why?), and you will get the web page from the server only if your server is listening at port 80.如果您省略“:6789”,浏览器将假定端口 80(为什么?),并且只有当您的服务器正在侦听端口 80 时,您才会从服务器获取 web 页面。

Then try to get a file that is not present on the server (eg, test.html).然后尝试获取服务器上不存在的文件(例如,test.html)。 You should get a “404 File Not Found” message.您应该会收到“未找到 404 文件”消息。

Part Two specification:第二部分规格:

Write your own HTTP client to test your server.编写您自己的 HTTP 客户端来测试您的服务器。 Your client will connect to the server using a TCP connection, send an HTTP request to the server, and display the server response as an output.您的客户端将使用 TCP 连接连接到服务器,向服务器发送 HTTP 请求,并将服务器响应显示为 output。 You can assume that the HTTP request sent is a GET method.您可以假设发送的 HTTP 请求是 GET 方法。 The client should take command line arguments specifying the server IP address or hostname, the port at which the server is listening, and the HTTP file name (eg, test.html or HelloWorld.html). The client should take command line arguments specifying the server IP address or hostname, the port at which the server is listening, and the HTTP file name (eg, test.html or HelloWorld.html). The following is an input command format to run the client.以下是运行客户端的输入命令格式。 webclient.py <server_host> <server_port> webclient.py <服务器主机> <服务器端口>

My code is for the Webserver is as follows:我的网络服务器代码如下:

#import socket module
from socket import *
import sys  # In order to terminate the program

serverSocket = socket(AF_INET, SOCK_STREAM)

# Prepare a sever socket
# Fill in start
serverHost = '192.168.1.4'
serverPort = 56014
serverSocket.bind((serverHost, serverPort))
serverSocket.listen(5)

# Fill in end
while True:
#establish connection
print('The server is ready to receive')

connectionSocket, addr = serverSocket.accept() # Fill in start             #Fill in end

try:

    message = connectionSocket.recv(4096) # Fill in start             #Fill in end

    filename = message.split()[1]

    f = open(filename[1:])

    outputdata = f.readlines() # Fill in start             #Fill in end

    # send one http header line in to the socket
    # Fill in start

    connectionSocket.send("HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n")
    connectionSocket.send("\r\n")

    # Fill in end

    # Send the content of the requested file to the connection socket
    for i in range(0, len(outputdata)):
        connectionSocket.send(outputdata[i].encode())
    connectionSocket.send("\r\n".encode())

    connectionSocket.close()

except IOError:
    # Send HTTP response code and message for file not found
    # Fill in start
    connectionSocket.send("HTTP/1.1 404 Not Found\r\n")
    connectionSocket.send("Content-Type: text/html\r\n")
    connectionSocket.send("\r\n")
    connectionSocket.send("<html><head></head><body><h1>404 Not Found</h1></body></html><\r\n>")

    # Fill in end
    # Close the client connection socket
    # Fill in start

    serverSocket.close()
    # Fill in end

serverSocket.close()
sys.exit()  # Terminate the program after sending the corresponding data

My code for the Webclient is as follows:我的 Webclient 代码如下:

from socket import *
import sys
serverName = sys.argv[1]
serverPort = int(sys.argv[2])
fileName = sys.argv[3]
request = "GET "+str(fileName)+" HTTP/1.1"

clientSocket = socket(AF_INET, SOCK_STREAM)
clientSocket.connect((serverName, serverPort))
clientSocket.send(request.encode())
returnFromSever = clientSocket.recv(4096)

while(len(returnFromSever)>0):
    print(returnFromSever.decode())
    returnFromSever = clientSocket.recv(4096)
clientSocket.close()

The error I am receiving is:我收到的错误是:

"No connection could be made because the target machine actively refused it" 

Admittedly, I know almost nothing about network related programming and on top of that I am not familiar with the Python syntax (my entire degree program was exclusively in Java) so I am very lost here and somewhat desperate.诚然,我对网络相关的编程几乎一无所知,最重要的是,我不熟悉 Python 语法(我的整个学位课程都是用 Java 编写的),所以我在这里非常迷茫,有些绝望。

If anyone could please point me in the right direction as far as how to correct this error, I would be very deeply grateful.如果有人可以就如何纠正这个错误指出我正确的方向,我将非常感激。

Thanks谢谢

The error you are getting ( No connection could be made because the target machine actively refused it ) means that the port you are trying to connect to is not not being listened on the server.您收到的错误( No connection could be made because the target machine actively refused it )意味着您尝试连接的端口没有在服务器上被监听。 For example, if you try to connect to 192.168.1.1:80 (IP = 192.168.1.1 , port= 80 ) and the server on 192.168.1.1 doesn't listen on port 80 , you would receive this error.例如,如果您尝试连接到192.168.1.1:80 (IP = 192.168.1.1 ,端口 = 80 )并且192.168.1.1上的服务器未侦听端口80 ,您将收到此错误。

A few things I would check in your case:我会在你的情况下检查几件事:

  1. Is your server IP actually 192.168.1.4 ?您的服务器 IP 实际上是192.168.1.4吗? If not, set it to the correct IP of the interface you want to listen on.如果不是,请将其设置为您要收听的接口的正确 IP。 If you want to listen on all the interfaces of the server, use this: serverHost = '0.0.0.0'如果要监听服务器的所有接口,请使用: serverHost = '0.0.0.0'
  2. Does your client code attempt to connect to the server port?您的客户端代码是否尝试连接到服务器端口? The server port is 56014 .服务器端口是56014 You need to pass it as the second parameter of your client program (because of this line serverPort = int(sys.argv[2]) ).您需要将其作为客户端程序的第二个参数传递(因为这一行serverPort = int(sys.argv[2]) )。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Python Socket 编程 - ConnectionRefusedError: [WinError 10061] 无法建立连接,因为目标机器主动拒绝了它 - Python Socket Programming - ConnectionRefusedError: [WinError 10061] No connection could be made because the target machine actively refused it Python-无法建立连接,因为目标计算机主动拒绝了它 - Python - No connection could be made because the target machine actively refused it Python:无法建立连接,因为目标机器主动拒绝它 - Python: No connection could be made because the target machine actively refused it 发送套接字时出错[WinError 10061]无法建立连接,因为目标计算机主动拒绝将Socket从Python发送到Android - Error sending socket [WinError 10061]No connection could be made because the target machine actively refused it for Socket from Python to Android Django Python - 无法建立连接,因为目标机器主动拒绝它 - Django Python - No connection could be made because the target machine actively refused it 套接字错误:无法建立连接,因为目标机器主动拒绝它 - Socket Error : No connection could be made because targeted machine actively refused it WinError 10061 由于目标机器主动拒绝,无法建立连接 - WinError 10061 No connection could be made because the target machine actively refused it “[WinError 10061] 无法建立连接,因为目标机器主动拒绝它” - "[WinError 10061] No connection could be made because the target machine actively refused it" EmailMultiAlternatives无法建立连接,因为目标计算机主动拒绝了它 - EmailMultiAlternatives no connection could be made because the target machine actively refused it 无法建立连接,因为目标计算机主动拒绝它 - No connection could be made because the target machine actively refused it
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM