Search in sources :

Example 51 with SocketException

use of java.net.SocketException in project robovm by robovm.

the class IoBridge method isConnected.

public static boolean isConnected(FileDescriptor fd, InetAddress inetAddress, int port, int timeoutMs, int remainingTimeoutMs) throws IOException {
    ErrnoException cause;
    try {
        StructPollfd[] pollFds = new StructPollfd[] { new StructPollfd() };
        pollFds[0].fd = fd;
        pollFds[0].events = (short) POLLOUT;
        int rc = Libcore.os.poll(pollFds, remainingTimeoutMs);
        if (rc == 0) {
            // Timeout.
            return false;
        }
        int connectError = Libcore.os.getsockoptInt(fd, SOL_SOCKET, SO_ERROR);
        if (connectError == 0) {
            // Success!
            return true;
        }
        // The connect(2) failed.
        throw new ErrnoException("isConnected", connectError);
    } catch (ErrnoException errnoException) {
        if (!fd.valid()) {
            throw new SocketException("Socket closed");
        }
        if (errnoException.errno == EINTR) {
            // Punt and ask the caller to try again.
            return false;
        } else {
            cause = errnoException;
        }
    }
    String detail = connectDetail(inetAddress, port, timeoutMs, cause);
    if (cause.errno == ETIMEDOUT) {
        throw new SocketTimeoutException(detail, cause);
    }
    throw new ConnectException(detail, cause);
}
Also used : SocketException(java.net.SocketException) SocketTimeoutException(java.net.SocketTimeoutException) ConnectException(java.net.ConnectException)

Example 52 with SocketException

use of java.net.SocketException in project jetty.project by eclipse.

the class IOTest method testHalfClose.

@Test
public void testHalfClose() throws Exception {
    ServerSocket connector = new ServerSocket(0);
    Socket client = new Socket("localhost", connector.getLocalPort());
    Socket server = connector.accept();
    // we can write both ways
    client.getOutputStream().write(1);
    assertEquals(1, server.getInputStream().read());
    server.getOutputStream().write(1);
    assertEquals(1, client.getInputStream().read());
    // shutdown output results in read -1
    client.shutdownOutput();
    assertEquals(-1, server.getInputStream().read());
    // Even though EOF has been read, the server input is not seen as shutdown
    assertFalse(server.isInputShutdown());
    // and we can read -1 again
    assertEquals(-1, server.getInputStream().read());
    // but cannot write
    try {
        client.getOutputStream().write(1);
        fail("exception expected");
    } catch (SocketException e) {
    }
    // but can still write in opposite direction.
    server.getOutputStream().write(1);
    assertEquals(1, client.getInputStream().read());
    // server can shutdown input to match the shutdown out of client
    server.shutdownInput();
    // now we EOF instead of reading -1
    try {
        server.getInputStream().read();
        fail("exception expected");
    } catch (SocketException e) {
    }
    // but can still write in opposite direction.
    server.getOutputStream().write(1);
    assertEquals(1, client.getInputStream().read());
    // client can shutdown input
    client.shutdownInput();
    // now we EOF instead of reading -1
    try {
        client.getInputStream().read();
        fail("exception expected");
    } catch (SocketException e) {
    }
    // But we can still write at the server (data which will never be read)
    server.getOutputStream().write(1);
    // and the server output is not shutdown
    assertFalse(server.isOutputShutdown());
    // until we explictly shut it down
    server.shutdownOutput();
    // and now we can't write
    try {
        server.getOutputStream().write(1);
        fail("exception expected");
    } catch (SocketException e) {
    }
    // but the sockets are still open
    assertFalse(client.isClosed());
    assertFalse(server.isClosed());
    // but if we close one end
    client.close();
    // it is seen as closed.
    assertTrue(client.isClosed());
    // but not the other end
    assertFalse(server.isClosed());
    // which has to be closed explictly
    server.close();
    assertTrue(server.isClosed());
}
Also used : SocketException(java.net.SocketException) ServerSocket(java.net.ServerSocket) Socket(java.net.Socket) ServerSocket(java.net.ServerSocket) Test(org.junit.Test)

Example 53 with SocketException

use of java.net.SocketException in project jetty.project by eclipse.

the class IOTest method testHalfCloseClientServer.

@Test
public void testHalfCloseClientServer() throws Exception {
    ServerSocketChannel connector = ServerSocketChannel.open();
    connector.socket().bind(null);
    Socket client = SocketChannel.open(connector.socket().getLocalSocketAddress()).socket();
    client.setSoTimeout(1000);
    client.setSoLinger(false, -1);
    Socket server = connector.accept().socket();
    server.setSoTimeout(1000);
    server.setSoLinger(false, -1);
    // Write from client to server
    client.getOutputStream().write(1);
    // Server reads
    assertEquals(1, server.getInputStream().read());
    // Write from server to client with oshut
    server.getOutputStream().write(1);
    // System.err.println("OSHUT "+server);
    server.shutdownOutput();
    // Client reads response
    assertEquals(1, client.getInputStream().read());
    try {
        // Client reads -1 and does ishut
        assertEquals(-1, client.getInputStream().read());
        assertFalse(client.isInputShutdown());
        //System.err.println("ISHUT "+client);
        client.shutdownInput();
        // Client ???
        //System.err.println("OSHUT "+client);
        client.shutdownOutput();
        //System.err.println("CLOSE "+client);
        client.close();
        // Server reads -1, does ishut and then close
        assertEquals(-1, server.getInputStream().read());
        assertFalse(server.isInputShutdown());
        try {
            server.shutdownInput();
        } catch (SocketException e) {
        // System.err.println(e);
        }
        //System.err.println("CLOSE "+server);
        server.close();
    } catch (Exception e) {
        System.err.println(e);
        assertTrue(OS.IS_OSX);
    }
}
Also used : SocketException(java.net.SocketException) AsynchronousServerSocketChannel(java.nio.channels.AsynchronousServerSocketChannel) ServerSocketChannel(java.nio.channels.ServerSocketChannel) Socket(java.net.Socket) ServerSocket(java.net.ServerSocket) SocketException(java.net.SocketException) IOException(java.io.IOException) Test(org.junit.Test)

Example 54 with SocketException

use of java.net.SocketException in project jetty.project by eclipse.

the class SSLEngineTest method testRequestJettyHttps.

@Test
public void testRequestJettyHttps() throws Exception {
    server.setHandler(new HelloWorldHandler());
    server.start();
    final int loops = 10;
    final int numConns = 20;
    Socket[] client = new Socket[numConns];
    SSLContext ctx = SSLContext.getInstance("TLSv1.2");
    ctx.init(null, SslContextFactory.TRUST_ALL_CERTS, new java.security.SecureRandom());
    int port = connector.getLocalPort();
    try {
        for (int l = 0; l < loops; l++) {
            // System.err.print('.');
            try {
                for (int i = 0; i < numConns; ++i) {
                    // System.err.println("write:"+i);
                    client[i] = ctx.getSocketFactory().createSocket("localhost", port);
                    OutputStream os = client[i].getOutputStream();
                    os.write(REQUEST0.getBytes());
                    os.write(REQUEST0.getBytes());
                    os.flush();
                }
                for (int i = 0; i < numConns; ++i) {
                    // System.err.println("flush:"+i);
                    OutputStream os = client[i].getOutputStream();
                    os.write(REQUEST1.getBytes());
                    os.flush();
                }
                for (int i = 0; i < numConns; ++i) {
                    // System.err.println("read:"+i);
                    // Read the response.
                    String responses = readResponse(client[i]);
                    // Check the responses
                    assertEquals(String.format("responses loop=%d connection=%d", l, i), RESPONSE0 + RESPONSE0 + RESPONSE1, responses);
                }
            } finally {
                for (int i = 0; i < numConns; ++i) {
                    if (client[i] != null) {
                        try {
                            assertEquals(-1, client[i].getInputStream().read());
                        } catch (SocketException e) {
                        }
                    }
                }
            }
        }
    } finally {
    // System.err.println();
    }
}
Also used : SocketException(java.net.SocketException) ServletOutputStream(javax.servlet.ServletOutputStream) OutputStream(java.io.OutputStream) SSLContext(javax.net.ssl.SSLContext) Socket(java.net.Socket) Test(org.junit.Test)

Example 55 with SocketException

use of java.net.SocketException in project SimplifyReader by chentao0707.

the class FileDownloadThread method downloadSegment.

/**
	 * 下载分片
	 * 
	 * @param info
	 * @return true下载完成;false下载失败或取消下载
	 */
private boolean downloadSegment(DownloadInfo info) {
    Logger.d("DownloadFlow", "FileDownloadThread: downloadSegment()");
    File f = checkAndGetFile(info);
    if (f == null) {
        cancel = true;
        info.setState(DownloadInfo.STATE_EXCEPTION);
        return false;
    }
    // 当前分片的结束位置
    final long endPosition = info.segsSize[info.segId - 1];
    // 当前分片的下载进度位置
    long curPosition = info.segDownloadedSize;
    if (curPosition >= endPosition) {
        // 当前分片已下载完成
        return true;
    }
    InputStream is = getInputStreamFromURL(info, download.canUseAcc());
    if (is == null) {
        cancel = true;
        info.setState(DownloadInfo.STATE_EXCEPTION);
        return false;
    }
    BufferedInputStream bis = null;
    BufferedOutputStream bos = null;
    try {
        bis = new BufferedInputStream(is);
        bos = new BufferedOutputStream(new FileOutputStream(f, true));
        int len = 0;
        byte[] buf = new byte[BUFFER_SIZE];
        while (cancel == false && curPosition < endPosition && info.getState() == DownloadInfo.STATE_DOWNLOADING && (len = bis.read(buf, 0, BUFFER_SIZE)) != -1 && cancel == false && info.getState() == DownloadInfo.STATE_DOWNLOADING) {
            // 因为read()是耗时操作,所以需要二次判断
            bos.write(buf, 0, len);
            curPosition += len;
            if (curPosition > endPosition) {
                Logger.d(TAG, "curPosition > endPosition,curPosition:" + curPosition + ",endPosition:" + endPosition);
                info.segDownloadedSize += (len - (curPosition - endPosition) + 1);
                info.downloadedSize += (len - (curPosition - endPosition) + 1);
            } else {
                info.segDownloadedSize = curPosition;
                info.downloadedSize += len;
            }
            info.setProgress(((double) info.downloadedSize * 100) / info.size);
            if (info.retry != 0)
                info.retry = 0;
            while (pause) {
                try {
                    sleep(500L);
                } catch (InterruptedException e) {
                }
            }
        }
        if (curPosition >= endPosition)
            return true;
    } catch (SocketTimeoutException e) {
        Logger.e("DownloadFlow", "FileDownloadThread: downloadSegment(): " + e.toString());
        Logger.e(TAG, e);
        if (info.getState() != DownloadInfo.STATE_PAUSE && info.getState() != DownloadInfo.STATE_CANCEL) {
            if (Util.hasInternet()) {
                info.setExceptionId(DownloadInfo.EXCEPTION_TIMEOUT);
                if (info.retry == 0) {
                    PlayerUtil.showTips(info.getExceptionInfo());
                }
            } else {
                info.setExceptionId(DownloadInfo.EXCEPTION_NO_NETWORK);
            }
            cancel = true;
            info.setState(DownloadInfo.STATE_EXCEPTION);
        }
    } catch (SocketException e) {
        Logger.e("DownloadFlow", "FileDownloadThread: downloadSegment(): " + e.toString());
        Logger.e(TAG, e);
        if (info.getState() != DownloadInfo.STATE_PAUSE && info.getState() != DownloadInfo.STATE_CANCEL) {
            if (Util.hasInternet()) {
                info.setExceptionId(DownloadInfo.EXCEPTION_TIMEOUT);
                if (info.retry == 0) {
                    PlayerUtil.showTips(info.getExceptionInfo());
                }
            } else {
                info.setExceptionId(DownloadInfo.EXCEPTION_NO_NETWORK);
            }
            cancel = true;
            info.setState(DownloadInfo.STATE_EXCEPTION);
        }
    } catch (FileNotFoundException e) {
        // SD卡被拔出
        Logger.e("DownloadFlow", "FileDownloadThread: downloadSegment(): " + e.toString());
        Logger.e(TAG, e);
        NotificationManager nm = (NotificationManager) YoukuPlayerApplication.context.getSystemService(Context.NOTIFICATION_SERVICE);
        nm.cancel(IDownload.NOTIFY_ID);
    } catch (IOException e) {
        Logger.e("DownloadFlow", "FileDownloadThread: downloadSegment(): " + e.toString());
        Logger.e(TAG, e);
        if (info.getState() != DownloadInfo.STATE_PAUSE && info.getState() != DownloadInfo.STATE_CANCEL) {
            // if (info.createTime < DownloadManager222.deleteAllTimestamp)
            // {
            // 如果删除后立马又创建了该视频,则需要重新删掉
            // download.deleteCache(info);
            // } else {
            String[] temp = info.savePath.split(YoukuPlayerApplication.getDownloadPath());
            SDCardManager m = new SDCardManager(temp[0]);
            if (!m.exist()) {
                info.setExceptionId(DownloadInfo.EXCEPTION_NO_SDCARD);
                PlayerUtil.showTips(info.getExceptionInfo());
            } else if (m.getFreeSize() - info.size <= 0) {
                info.setExceptionId(DownloadInfo.EXCEPTION_NO_SPACE);
                PlayerUtil.showTips(info.getExceptionInfo());
            }
            cancel = true;
            info.setState(DownloadInfo.STATE_EXCEPTION);
        // }
        }
    } finally {
        try {
            if (bos != null)
                bos.close();
            if (bis != null)
                bis.close();
            if (is != null)
                is.close();
        } catch (IOException e) {
        }
    }
    return false;
}
Also used : SocketException(java.net.SocketException) NotificationManager(android.app.NotificationManager) BufferedInputStream(java.io.BufferedInputStream) InputStream(java.io.InputStream) FileNotFoundException(java.io.FileNotFoundException) IOException(java.io.IOException) SocketTimeoutException(java.net.SocketTimeoutException) BufferedInputStream(java.io.BufferedInputStream) FileOutputStream(java.io.FileOutputStream) File(java.io.File) BufferedOutputStream(java.io.BufferedOutputStream)

Aggregations

SocketException (java.net.SocketException)523 IOException (java.io.IOException)189 InetAddress (java.net.InetAddress)127 NetworkInterface (java.net.NetworkInterface)110 Socket (java.net.Socket)100 UnknownHostException (java.net.UnknownHostException)93 ServerSocket (java.net.ServerSocket)82 DatagramSocket (java.net.DatagramSocket)78 SocketTimeoutException (java.net.SocketTimeoutException)77 InetSocketAddress (java.net.InetSocketAddress)62 Test (org.junit.Test)50 ConnectException (java.net.ConnectException)39 DatagramPacket (java.net.DatagramPacket)38 ArrayList (java.util.ArrayList)35 BindException (java.net.BindException)31 Inet4Address (java.net.Inet4Address)24 SocketAddress (java.net.SocketAddress)24 InterruptedIOException (java.io.InterruptedIOException)23 IllegalBlockingModeException (java.nio.channels.IllegalBlockingModeException)23 SmallTest (android.test.suitebuilder.annotation.SmallTest)20