我使用OpenCV for Android编写一个套接字,将图像传输到用Python编写的服务器。
这个应用程序是基于OpenCV for Android v2.4.8给出的教程3。它的工作原理如下:当用户触摸屏幕时,图像被捕获并存储在手机的内部存储器中。该图像随后通过套接字传输。
问题是,套接字连接从未建立后,图像被捕获,我不知道为什么。这是onTouch(View v, MotionEvent event)
@SuppressLint("SimpleDateFormat")
@Override
public boolean onTouch(View v, MotionEvent event) {
Log.i(TAG,"onTouch event");
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss");
String currentDateandTime = sdf.format(new Date());
fileName = Environment.getExternalStorageDirectory().getPath() +
"/sample_picture_" + currentDateandTime + ".jpg";
mOpenCvCameraView.takePicture(fileName);
Toast.makeText(this, fileName + " saved", Toast.LENGTH_SHORT).show();
StartSocket();
return false;
}
这是StartSocket()
的代码。请注意,我已经在另一个Android应用程序中尝试了这段代码,通过套接字发送文本文件,并且成功了。
private void StartSocket() {
Log.d("SEND","about to imread the img");
img = Highgui.imread(fileName);
Log.d("SEND","just finished with imread");
Thread t = new Thread(new Runnable(){
@Override
public void run() {
try {
Socket s = new Socket("192.168.19.128", 6000);
//--- SEND IMAGE TO SERVER ---//
byte[] data = new byte[(int) (img.total()*img.channels())];
img.get(0,0,data);
DataOutputStream dout = new DataOutputStream(s.getOutputStream());
dout.write(data);
dout.flush();
//--- RECEIVE TEXT FROM SERVER ---//
int charsRead = 0;
char[] buffer = new char[1024];
Log.d("RECEIVE","about to receive");
BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));
while ((charsRead = in.read(buffer)) != -1) {
serverMsg += new String(buffer).substring(0, charsRead);
Log.d("Received char",serverMsg);
}
Log.d("Received msg",serverMsg); */
mHandler.post(new Runnable() {
@Override
public void run() {
msgReceived = (TextView) findViewById(R.id.msgReceived);
msgReceived.setText(serverMsg);
}
});
dout.close();
s.close(); //close socket
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
});
t.start();
}
谁能指导我什么可能是套接字连接没有建立的原因?请注意,所有必要的权限都已添加到清单中。
我发现问题出在网络上。我在一个基于linux的虚拟机上运行服务器,该虚拟机没有与局域网桥接。因此,抛开代码中的其他问题(比如在服务器端接收损坏的图像),套接字连接成功建立。