我是Python的新手并且有一个基本问题,网络套接字连接的客户端是否可以接收数据?在我的问题中,客户端是启动连接的人,这可能很明显,但我想明确。我问,因为我有另一个服务器和客户端(都是python),允许服务器从客户端接收文件。它工作得很好,但我无法得到一个客户端收到文件的例子。 Python一直告诉我管道已经坏了,我怀疑它是因为在客户端我使用了行data = mysocket.recv(1024)
。我怀疑客户端看不到任何数据流,从而关闭了与服务器的连接。服务器将其视为损坏的管道。服务器和客户端在下面。
服务器:
#libraries to import
import socket
import os
import sys
import M2Crypto as m2c
#information about the server the size of the message being transferred
server_address = '10.1.1.2'
key_port = 8888
max_transfer_block = 1024
FILE = open("sPub.pem","r")
#socket for public key transfer
keysocket = socket.socket( socket.AF_INET, socket.SOCK_STREAM)
keysocket.bind((server_address, key_port))
keysocket.listen(1)
while 1:
conn, client_addr = keysocket.accept()
print 'connected by', client_addr
#sends data to the client
data = FILE.read()
keysocket.sendall(data)
keysocket.close()
客户端:
# the specified libraries
import socket
import M2Crypto as m2c
#file to be transferred
FILE = open("test.txt", "r")
#address of the server
server_addr = '10.1.1.2'
#port the server is listening on
dest_port = 8888
data = FILE.read()
#Creates a socket for the transfer
mysocket = socket.socket( socket.AF_INET, socket.SOCK_STREAM)
mysocket.connect( (server_addr, dest_port) )
data = mysocket.recv(1024)
print data
#creates a new file to store the msg
name = "serverPubKey.pem"
#opens the new file and writes the msg to it
FILE = open (name, "w")
FILE.write(data)
#closes the socket.
mysocket.close()
我很感激有关此事的任何帮助。谢谢!
答案 0 :(得分:1)
在这样的应用程序中,绕过低级详细信息并使用socket.makefile代替更高级别的API有时会很有帮助。
在客户端关闭时,替换:
data = mysocket.recv(1024)
使用:
f = mysocket.makefile('rb')
data = f.read(1024) # or any other file method call you need
source code for ftplib显示了如何在生产代码中执行此操作。
答案 1 :(得分:0)
此外,添加到之前的评论,有时候一个好的测试是重复接收几次。一次通过捕获服务器发送的信息的可能性不大。
类似这样的事情
nreceive = True#nreceive = Not Received
ticks = 0
f = None
while nreceive and ticks < 101:#try to get the info 100 times or until it's received
ticks+=1
try:
f = mysocket.makefile('rb')
if not f == None:
nreceive = False
except:
pass
data = f.read(1024)