我有以下问题:我有一个 Android 应用程序,它将图片发送到 C++ 服务器,该服务器计算一些参数并将它们发送回客户端。但是当发送文件并计算所有内容时,手机无法接收消息,并且我的 LogCat 显示“Socket Closed”。
但是如果我注释掉发送和接收图像的代码,客户端就能够从服务器接收到一条消息。为什么在发送图像之后这是不可能的?
这是我的相关代码:
安卓:
String picturePath = "/sdcard/DCIM/Camera/IMG_0004.jpg";
final File picture = new File(picturePath);
if (picture.exists()) {
try {
//reading file and sending to server
FileInputStream fis = new FileInputStream(picture);
Log.d(TAG, "trying to connect");
String st = "laber";
Socket s = new Socket("192.168.0.12", port);
tv = (TextView) findViewById(R.id.textDesc);
tv.setText(st);
OutputStream out = s.getOutputStream();
DataInputStream in = new DataInputStream (s.getInputStream());
byte[] buf = new byte[1024];
int read = 0;
int totBytes = 0;
while ((read = fis.read(buf)) != -1)
{
totBytes = totBytes + read;
out.write(buf, 0, read);
Log.d(TAG, "Image - Read: " + read + " - Total " + totBytes + " bytes!");
}
out.flush();
out.close();
st = in.readLine();
fis.close();
Log.d(TAG, "Waiting" + " "+ st+ " " +st.compareTo("laber"));
tv.setText(st);
// Close connection
s.close();
Log.d(TAG, "connection closed " + st);
dataReceived=true;
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
C++
SOCKET TempSock=SOCKET_ERROR;
while(TempSock==SOCKET_ERROR)
{
std::cout<<"Waiting for incoming connections...\r\n";
TempSock=accept(Socket,NULL,NULL);
}
Socket=TempSock;
int totalBytes = 0;
ofstream outFile;
char buf[1024] = "";
int received = 0;
if (outFile != NULL)
{
outFile.open("C:\\test\\ReceivedFiles\\test.jpg" , ofstream::binary);
cout << "File opened!" << endl;
} else
{
cout << "Can't open file!" << endl;
}
//receiving file and writing to disk
while ((received = recv(Socket, buf, sizeof(buf), 0)) > 0)
{
cout << "R:" << received << " ";
if (received > 0)
{
totalBytes += received;
if (outFile.is_open())
{
outFile.write(buf, received);
cout << " (Total: " << totalBytes << " B)" << endl;
} else
cout << "Error in recv() function, received bytes = " << received << endl;
} else
cout << "R:" << received << " ";
}
std::cout<<"Client connected!\r\n\r\n";
initImageSearch();
readFiles();
keypointMatching();
searchBundleOut();
ransacMatrices();
getRotationOrientation();
//send message back to client
string message = doubleToString(viewingDirectionArray[0])+" "+doubleToString(viewingDirectionArray[1])+" "+doubleToString(viewingDirectionArray[2])+" "+doubleToString(positionArray[0])+" "+doubleToString(positionArray[1])+" "+doubleToString(positionArray[2])+" 0.5 0.5 0.5 baum";
const char *szMessage;
szMessage = "123 456 789 246 135 178 189";//message.c_str();
int msg = send(Socket,szMessage,strlen(szMessage),0);
std::cout<<msg<<endl;
// Shutdown socket
shutdown(Socket,SD_SEND);
// Close socket entirely
closesocket(Socket);
// Cleanup Winsock
WSACleanup();