私は次の問題を抱えています: 私は、いくつかのパラメーターを計算してクライアントに送り返す C++ サーバーに画像を送信する Android アプリケーションを持っています。しかし、ファイルが送信され、すべてが計算されると、電話はメッセージを受信できず、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();