我试图通过在python 3.4中使用套接字服务器来接收img,并且客户端正在使用android.I已经完成了写img.But问题是客户端关闭了img文件,然后连接也会断开连接。我该如何解决这个问题?
我的服务器代码如下:
import socket
import struct
import sys
address = ("10.0.0.22", 5000)
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
except (socket.error, msg):
print ('Failed to create socket.Error code:' + str(msg[0]) + ', Error message: ' + msg[1])
sys.exit()
print ('Socket Created')
s.bind(address)
s.listen(5)
while True:
(client, addr) = s.accept()
print ('got connected from', client,addr)
buf = b''
while len(buf)<4:
buf += client.recv(4-len(buf))
size = struct.unpack('!i', buf)
print ("receiving %s bytes" % size)
with open('tst.jpg', 'wb') as img:
while True:
data = client.recv(1024)
print (data)
if not data:
break
img.write(data)
img.close()
print ('received, yay!')
#write json file
...
with open('a.json','r+') as data_file:
data = json.dumps(json.load(data_file)).encode('utf-8')
client.sendall(data)
print('send json, yay!')
client.close()
我的客户端代码如下
FileOutputStream fop;
Socket socket;
try {
fop=new FileOutputStream("/sdcard/dd.jpg");
bmp.compress(Bitmap.CompressFormat.JPEG, 100, fop);
fop.close();
Toast.makeText(MainActivity.this, "saved",Toast.LENGTH_LONG).show();
InetAddress serverAdd = InetAddress.getByName("10.0.0.22");
SocketAddress sc_add = new InetSocketAddress(serverAdd,5000);
socket = new Socket();
socket.connect(sc_add,2000);
DataOutputStream out = new DataOutputStream(socket.getOutputStream());
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] bytes = baos.toByteArray();
out.write(bytes);
out.close();
out.flush();
InputStream inputStream = socket.getInputStream();
byte buffer[] = new byte[1024 * 4];
int temp = 0;
while ((temp = inputStream.read(buffer) != -1)){
System.out.println(new String(buffer,0,temp));
}
socket.close();
}