我正在尝试使用Python的套接字编程发送图像文件。我能够发送文本文件,但一直在尝试发送图像文件。我打开并读取图像文件内容到字符串中,然后将其发送,并在客户端接收并写入以不同目录下相同名称的文件中,但我无法打开该文件。同时,我会附上我的代码。注释部分表明我已经尝试过了。此外,我还遇到了发送整数
这是服务器脚本:
size
的问题,但在另一端收到了随机字符串。这是服务器脚本:
import socket
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind(("", 5000))
server_socket.listen(5)
import os
client_socket, address = server_socket.accept()
print "Conencted to - ",address,"\n"
while (1):
choice = client_socket.recv(1024)
choice = int(choice)
if(choice == 1):
data = client_socket.recv(1024)
print "The following data was received - ",data
print "Opening file - ",data
fp = open(data,'r')
strng = fp.read()
size = os.path.getsize(data)
size = str(size)
client_socket.send(size)
client_socket.send (strng)
#client_socket.close()
if (choice == 2):
data = client_socket.recv(1024)
print "The following data was received - ",data
print "Opening file - ",data
fp = open(data,'r')
strng = fp.read()
#strng = str(fp)
size = os.path.getsize(data)
print size
size = str(size)
print size
client_socket.send(size)
client_socket.send (strng)
#client_socket.close()
这是客户端脚本 -
#!/usr/bin/python
# TCP client example
import socket,os
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client_socket.connect(("", 5000))
k = ' '
size = 1024
while(1):
print "Do you want to transfer a \n1.Text File\n2.Image\n3.Video\n"
k = raw_input()
client_socket.send(k)
k = int (k)
if(k == 1):
print "Enter file name\n"
strng = raw_input()
client_socket.send(strng)
size = client_socket.recv(1024)
size = int(size)
print "The file size is - ",size," bytes"
size = size*2
strng = client_socket.recv(size)
print "\nThe contents of that file - "
print strng
if (k==2):
print "Enter file name of the image with extentsion (example: filename.jpg,filename.png) - "
fname = raw_input()
client_socket.send(fname)
size = client_socket.recv(1)
print size
#size = int(size)
print "The file size is - ",size
size = size*2
strng = client_socket.recv(256456)
print "\nThe file will be saved and opened- "
fname = 'downloads/'+fname
nf = open(fname,'w')
nf.write(strng)
nf.close()
fname = 'viewnior '+ fname
print fname
os.system(fname)
我正在使用 Crunchbang Linux——一款非官方的基于 Debian 的发行版,viewnior 是图片查看器。
print repr(client)
? - Glaslos