我想编写一个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
我在Mac OS X上运行Python 2.7.11。
我试过很多搜索没有解决方案。
答案 0 :(得分:0)
在服务器而不是
serverSocket.bind(('127.0.0.1', 8000))
DO
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