我正在使用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();
}
任何人都可以指导我找出未建立套接字连接的原因吗?请注意,所有必要的权限都会添加到清单中。
答案 0 :(得分:1)
我发现问题出在网络上。我在基于Linux的虚拟机上运行服务器,该虚拟机没有与LAN桥接。 因此,我的代码丢弃了其他问题(比如在服务器端接收损坏的图像),套接字连接成功建立。