我完美地接收Android
来自C# Server
和流式视频的图像。问题是,我总是为每个图像打开和关闭套接字。如何仅在创建单个套接字时接收图像。任何帮助,将不胜感激。
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv=(TextView)findViewById(R.id.textView1);
etip=(EditText)findViewById(R.id.editText1);
// etip.setText("192.168.1.5");
etip.setText("10.0.2.2");
imgview=(ImageView)findViewById(R.id.imageView1);
btn=(Button)findViewById(R.id.button1);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
try {
try {
serverAddr = InetAddress.getByName(etip.getText().toString());
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Log.d("TCP", "C: Connecting...");
}
finally
{
}
try
{
{
mHandler = new Handler();
mHandler.post(connectSocket);
}
}
catch(Exception ex)
{
}
}
});
}
private Runnable connectSocket=new Runnable() {
@Override
public void run() {
{
try {
socket = new Socket(serverAddr, 4444);
DataInputStream dis;
try {
dis=new DataInputStream(socket.getInputStream());
int bytesRead;
byte[] pic = new byte[5000*1024];
bytesRead = dis.read(pic, 0, pic.length);
bitmapimage = BitmapFactory.decodeByteArray(pic, 0, bytesRead);
} catch(Exception e) {
Log.e("TCP", "S: Error", e);
} finally {
socket.close();
}
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
Log.e("TCP", "C: UnknownHostException", e);
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
Log.e("TCP", "C: IOException", e);
e.printStackTrace();
}
imgview.setImageBitmap(bitmapimage);
imgview.invalidate();
}
mHandler.postDelayed(this, 0);
} //run end
};
}