在Android

时间:2015-09-28 15:50:19

标签: java android sockets udp datagram

我正在创建一个必须通过Wi-Fi和UDP协议接收压缩视频流的应用程序。视频流源是带有ARM微控制器和WLAN模块的DIY项目。尝试重新连接时遇到问题。当我第一次将learnObject var设置为true时,一切都可以。但是当我关闭该连接调用closeUdpSocket()然后尝试连接一次时出现错误。错误是:java.net.SocketTimeoutException 在libcore.io.IoBridge.maybeThowAfterRecvForm(IoBridge.java:551)。你觉得怎么回事? 谢谢你的帮助

    public CameraView(Context context) {
        super(context);
        // TODO Auto-generated constructor stub
        surfaceHolder = getHolder();

        // Create Bitmap for video frame
        bitmap = Bitmap.createBitmap(WIDTH, HEIGHT, Bitmap.Config.ARGB_8888/*Bitmap.Config.ALPHA_8*//*Bitmap.Config.RGB_565*/);
        screenRect = new Rect(0, 0, 680, 510);

        // Create and set paint color and its transparency
        paint = new Paint(Paint.ANTI_ALIAS_FLAG);
//      paint.setARGB(100, 255, 0, 0);

        // Prepare for drawing Rects
        outerRect = new Rect(0, 0, 0, 0);
        innerRect = new Rect(0, 0, 0, 0);

        Log.d("S3", "stworzono bitmape");
    }

    public void onResumeCameraView() {
        running = true;
        thread = new Thread(this);
        thread.start();
    }

    public void onPauseCameraView() {
        boolean retry = true;
        running = false;
        while (retry) {
            try {
                thread.join();
                retry = false;
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

    @Override
    public void run() {
        long ticksPS = 1000 / FPS;
        long startTime;
        long sleepTime;
        int blobx = MainActivity.blobx, bloby = MainActivity.bloby, blobw = MainActivity.blobw, blobh = MainActivity.blobh;
        Canvas canvas;
        int len = 0, n, j;

        // TODO Auto-generated method stub
        while (running) {
            startTime = System.currentTimeMillis();

            if (!/*isSurfaceCreated*/surfaceHolder.getSurface().isValid()) {
                continue;
            }

            if (MainActivity.wlanStatus == 1)
                Log.d("S3", "wlan activ");
            else if (MainActivity.wlanStatus == 2)
                Log.d("S3", "wlan deactivated");
            else if (MainActivity.wlanStatus == 3)
                Log.d("S3", "wlan error occured");

//          canvas = null;
            // try locking the canvas for exclusive pixel editing
            // in the surface
//          try {

                // Create Canvas and set white background color
                canvas = surfaceHolder.lockCanvas();
//              synchronized (surfaceHolder) {
                    canvas.drawColor(0xFF5C5C5C);

                    if (MainActivity.learnObject == false && MainActivity.wlanStatus == MainActivity.WLAN_STATUS_DEINITIALIZED) {
                        MainActivity.wlanStatus = MainActivity.WLAN_STATUS_OFF;
                        closeUdpSocket();
                        Log.d("S3", "Socket zamkniety");
                    }
                    if (MainActivity.learnObject == true && MainActivity.wlanStatus == MainActivity.WLAN_STATUS_INITIALIZED) {
                        MainActivity.wlanStatus = MainActivity.WLAN_STATUS_RUNNING;
                        createUdpSocket();
                        Log.d("S3", "Socket utworzony");
                    }

                    if (MainActivity.learnObject && (MainActivity.wlanStatus == MainActivity.WLAN_STATUS_RUNNING)) {
                        buffer.rewind();
                        try {
                            sock.send(header);

                            if (D)
                                Log.d(TAG,"Start of receiving jpeg.");

                            len = 0;
                            j = 0;
                            do {
                                sock.receive(packet);
                                n = packet.getLength();
                                buffer.put(packet.getData(), 0, n);

                                if (D) {
                                    Log.d(TAG, "Read: " + n + " bytes");
                                    ++j;
                                }

                                len += n;
        //                      packet.setLength(1024);
                            } while (n == 1024);
                            if (D)
                                Log.d(TAG, "End of receiving jpeg, received: " + j + " packets");

                        } catch (IOException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }

                        buffer.rewind();

                            if(frameData == null) { // do it only once at the beginning
                                frameData = new byte[IMAGE_SIZE];

                                if(D)
                                    Log.d(TAG, "Memory allocated for frameData: " + IMAGE_SIZE);

                            }

                            buffer.get(frameData, 0, len);  // copy data from main buffer into temporary frameData buffer
                        try {   
                            retval = pixeltobmp(frameData, len, bitmap);    // for mjpeg decoding we can use this external jpeg library
        //                  bitmap = BitmapFactory.decodeStream(new ByteArrayInputStream(frameData, 0, len));   // or this Java built-in library 
        //                  bitmap = BitmapFactory.decodeByteArray(frameData, 0, len);  // or this Java built-in library 

                            if ((bitmap != null) && (retval == 0)) {    // check if new bitmap is available
                                canvas.drawBitmap(bitmap, null, screenRect, paint);
                            } else {
                                if (D)
                                    Log.d(TAG,"Error: Can't decode the incoming data");
                            }

                            freeCameraMemory();
                        } catch (Exception e) {}
                    }
//              }
//          } finally {
//             // in case of an exception the surface is not left in 
//             // an inconsistent state
//             if (canvas != null) {
//                 surfaceHolder.unlockCanvasAndPost(canvas);
//             }
//          }   // end finally

            surfaceHolder.unlockCanvasAndPost(canvas);

//          SystemClock.sleep(10000);

            sleepTime = ticksPS-(System.currentTimeMillis() - startTime);
            try {
                   if (sleepTime > 0) {
                          Thread.sleep(sleepTime);
                   }
                   else {
                          Thread.sleep(10);
                   }
            } catch (Exception e) {}
        }
    }

    private void createUdpSocket()
    {
        try {
            sock = new DatagramSocket();
            sock.setSoTimeout(500); // 10000
            header = new DatagramPacket("HEADER".getBytes(), 6, InetAddress.getByName(SERVER_ADDR), SERVER_PORT);
            packet = new DatagramPacket(new byte[1024], 1024);
        } catch (SocketException e) {
            // TODO Auto-generated catch block
            Toast.makeText(getContext(), "Error: Can't create Socket", Toast.LENGTH_SHORT).show(); 
            e.printStackTrace();
        } catch (UnknownHostException e) {
            // TODO Auto-generated catch block
            Toast.makeText(getContext(), "Error: Invalid Host IP Address", Toast.LENGTH_SHORT).show(); 
            e.printStackTrace();
        }   
    }

    private void closeUdpSocket()
    {
        if (sock != null)
            sock.close();
    }
}

0 个答案:

没有答案