【发布时间】:2021-11-24 01:33:19
【问题描述】:
正在学习套接字编程,我的两个代码之间出现了一个奇怪的问题,这取决于我尝试运行它们的 IP。
服务器:
import socket
import time
import datetime
import filecmp
HOST = 'localhost'
PORT = 9100
n = 1
x = 0
average_list = []
print('I am ready for any client side request \n')
file_comparison = "send.txt"
s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind((HOST,PORT))
s.listen(1)
conn, addr = s.accept()
while n <= 100:
data = conn.recv(1024)
file = 'receive1.txt';
print('I am starting receiving file', file,'for the',n,'th time')
a = datetime.datetime.now()
f = open(file, 'wb')
f.write(data)
print('I am finishing receiving file', file,'for the',n,'th time')
b = datetime.datetime.now()
rawtime = b - a
millidelta = rawtime * 1000
average_list.append(millidelta)
real_average = ((sum(average_list, datetime.timedelta(0,0))) / n)
print('The time used in milliseconds to receive',file,'for the',n,'th time','is:',millidelta,'milliseconds')
print('The average time to receive',file,'in milliseconds is:',real_average)
if filecmp.cmp(file,file_comparison,shallow=False):
x = x+1
n=n + 1
f.close()
conn.close()
s.close()
print('I am done \n')
print('Total errors: ',x,'out of',n-1 )
客户:
import socket
import datetime
import time
import filecmp
#initializing host, port, filename, total time and number of times to send the file
host = 'localhost'
port = 9100
fileName = "send.txt"
n = 1
average_list = []
file_to_send = open(fileName,'rb')
while n <= 100:
data = file_to_send.read(1024)
s=socket.socket()
s.connect((host,port))
s.sendall(data)
#reading the next 1024 bits
print('I am connecting to server side:',host,'\n')
print('I am sending file',fileName,'for the',n,'th time')
a = datetime.datetime.now()
print('I am finishing sending file',fileName,'for the',n,'th time')
b = datetime.datetime.now()
rawtime = b - a
millidelta = rawtime * 1000
average_list.append(millidelta)
real_average = ((sum(average_list, datetime.timedelta(0,0))) / n)
print('The time used in milliseconds to send',fileName,'for the',n,'th time','is:',millidelta,'milliseconds')
print('The average time to send',fileName,'in milliseconds is:',real_average)
n = n + 1
file_to_send.close()
s.close()
print('I am done')
在当前的迭代中,我的客户端代码只是在循环中运行,试图将 .txt 文件的数据发送到没有接收任何内容的服务器。如果我将 'localhost' 更改为我的实际 IP 地址,我会让服务器端代码在其 while 循环中循环,而客户端在 2 次迭代后放弃:
ConnectionRefusedError: [WinError 10061] 由于目标机器主动拒绝,无法建立连接
引用第 15 行的错误,“s.connect((host,port)) 是问题的原因。最终我卡住了,因为在我认为是两个正确的主机实现之间更改我的主机给了我极大的不同的结果,两者都没有按预期工作。
【问题讨论】:
-
您确定没有在 localhost:9100 上运行另一个副本...尝试将端口更改为其他 9121 或两个文件中的其他内容,然后启动服务器然后启动客户端...使用localhost 或 127.0.0.1 作为客户端的 ip,并使用 0.0.0.0 作为服务器的 ip
-
请记住,套接字连接发生在每个网卡上。如果你的服务器绑定到
localhost,那么它只会监听本地主机接口。它不会列在外部 IP 地址上,即使它发往同一台计算机。如果你想让它在所有接口上监听,你必须绑定到"0.0.0.0"。 -
你好。我按照您的建议进行了更改,然后又在我的客户端代码@Joran Beasley 上产生了 WinError 10061