我是python套接字编程的新手。这是在Mininet主机中打开TCP套接字并将照片从一台主机发送到另一台主机的示例。实际上,为了满足我的要求,我已经更改了用于向其他主机(writing the received data to a text file)发送简单消息的代码。 但是,当我运行这段代码时,我在发送方遇到了这个错误:
144
Traceback (most recent call last):
File mmyClient2,pym, line 13, in <module>
if(s.sendall(data)):
File m/usr/lib/python2.7/socket.pym, line 228, in meth
return yetattr[self,_sockename](*args)
File m/usr/lib/python2.7/socket.pym, line 174, in _dummy
raise error(EBADF, 'Bad file descriptor')
socket,error: [Errno 9] Bad file descriptor
那怎么了?
Receiver.py
import socket
import sys
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind(('10.0.0.1', 12345))
buf = 1024
f = open("2.jpg",'wb')
s.listen(1)
conn , addr = s.accept()
while 1:
data = conn.recv(buf)
print(data[:10])
#print "PACKAGE RECEIVED..."
f.write(data)
if not data: break
#conn.send(data)
conn.close()
s.close()
Sender.py:
import socket
import sys
f=open ("1.jpg", "rb")
print sys.getsizeof(f)
buf = 1024
data = f.read(buf)
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(('10.0.0.1',12345))
while (data):
if(s.sendall(data)):
#print "sending ..."
data = f.read(buf)
#print(f.tell(), data[:10])
s.close()
s.sendall()似乎有问题,因为当我将其更改为s.send()时,没有错误,并且照片传输成功。所以我的问题是:尽管在此站点上的上一个问题中建议我使用s.sendall()而不是s.send(),但不这样做是错误的吗?
答案 0 :(得分:1)
发送完所有数据后,您关闭了套接字,然后再次使用关闭的套接字,这会导致错误。您可以像这样编写发件人。
import socket
import sys
f=open ("1.jpg", "rb")
print sys.getsizeof(f)
buf = 1024
data = f.read(buf)
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(('10.0.0.1',12345))
while 1:
if not data:
break
s.sendall(data)
data = f.read(buf)
s.close()