Socket.error:[Errno 61]连接被拒绝Python

2024-10-06 20:25:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我想编写一个HTTP客户端来测试web服务器。客户端将使用TCP连接。

#Import socket module
from socket import *
import sys
server_host = sys.argv[1]
server_port = int(sys.argv[2])
filename = sys.argv[3]

clientSocket = socket(AF_INET,SOCK_STREAM)
clientSocket.connect((server_host,server_port))

while True:
    print 'Ready to server...'
    connectionSocket, addr = clientSocket.accept()
    print 'connected from', addr
    try:
        f = open(filename[1:])
        outputdata = f.read()
        #Send one HTTP header line into socket
        connectionSocket.sendall('\nHTTP/1.1 200 OK\r\n\r\n')
        #Send the content of the requested file to the client
        for i in range(0, len(outputdata)):  
            connectionSocket.sendall(outputdata[i])
        #Closes the socket for this client
        connectionSocket.close()
        print 'File Received'
    except IOError:
        print 'IOError'
        #Send response message for file not found
        connectionSocket.sendall('\n404 Not Found\n') 
        #Close client socket 
        connectionSocket.close()
clientSocket.close()

命令lind输入为:

python  ./client.py  127.0.0.1  8000  HelloWorld.html

此脚本输出:

Traceback (most recent call last):File "./client.py", line 9, in <module>
clientSocket.connect((server_host,server_port))
File"/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/socket.py", line 228, in meth
return getattr(self._sock,name)(*args)
socket.error: [Errno 61] Connection refused

我在MacOSX上运行Python2.7.11

我试着到处找了很多没有解决的办法。


Tags: theclientsendhostserverportsysline
1条回答
网友
1楼 · 发布于 2024-10-06 20:25:19

在服务器中而不是

serverSocket.bind(('127.0.0.1', 8000))

serverSocket.bind(('<LAN/Local IP address>', 8000))

示例:

serverSocket.bind(('192.168.1.131', 8000))

当然,您也将在客户端使用相同的本地IP地址。

示例:

python  ./client.py  192.168.1.131  8000  HelloWorld.html

相关问题 更多 >