Search in sources :

Example 86 with SocketException

use of java.net.SocketException in project remusic by aa112901.

the class RequestDealThread method processRequest.

private void processRequest(HttpURLConnection request, Socket client) throws IllegalStateException, IOException {
    if (request == null) {
        return;
    }
    try {
        byte[] audioCache = null;
        // 得到MediaPlayer原始请求Range起始
        originRangeStart = getRangeStart(request);
        Log.i(LOG_TAG, "原始请求Range起始值:" + originRangeStart + " 本地缓存长度:" + fileUtils.getLength());
        // 缓存的文件大小
        int cacheFileSize = cacheDao.getFileSize(fileUtils.getFileName());
        /*
             * 如果缓存完成,无需发送请求,本地缓存返回MediaPlayer。
			 */
        if (fileUtils.isEnable() && fileUtils.getLength() == cacheFileSize) {
            audioCache = fileUtils.read(originRangeStart, Constants.AUDIO_BUFFER_MAX_LENGTH);
            sendLocalHeaderAndCache(originRangeStart, cacheFileSize - 1, cacheFileSize, audioCache);
            return;
        }
        /*
             * 请求Range起始值和本地缓存比对。如果有缓存,得到缓存内容,修改Range。 如果没有缓存,则Range不变。
			 */
        if (fileUtils.isEnable() && originRangeStart < fileUtils.getLength()) {
            audioCache = fileUtils.read(originRangeStart, Constants.AUDIO_BUFFER_MAX_LENGTH);
            Log.i(LOG_TAG, "本地已缓存长度(跳过):" + audioCache.length);
            // 得到需要发送请求Range Start(本地缓存结尾位置+1=缓存长度)
            realRangeStart = fileUtils.getLength();
            // 替换请求Header
            request.setRequestProperty(Constants.RANGE, Constants.RANGE_PARAMS + realRangeStart + "-");
        //	request.removeHeaders(Constants.RANGE);
        //	request.addHeader(Constants.RANGE, Constants.RANGE_PARAMS + realRangeStart + "-");
        } else {
            realRangeStart = originRangeStart;
        }
        // 缓存是否已经到最大值(如果缓存已经到最大值,则只需要返回缓存)
        boolean isCacheEnough = (audioCache != null && audioCache.length == Constants.AUDIO_BUFFER_MAX_LENGTH) ? true : false;
        // 缓存足够&&有文件大小
        if (isCacheEnough && cacheFileSize > 0) {
            sendLocalHeaderAndCache(originRangeStart, cacheFileSize - 1, cacheFileSize, audioCache);
        } else // 缓存不够。或者数据库没有文件大小
        {
            HttpURLConnection realResponse = null;
            // 如果数据库没有存文件大小,则获取(处理数据库没有文件大小的情况)
            if (cacheFileSize <= 0) {
                Log.d(LOG_TAG, "数据库未包含文件大小,发送请求");
                realResponse = HttpUtils.send(request);
                if (realResponse == null) {
                    return;
                }
                cacheFileSize = getContentLength(realResponse);
            }
            sendLocalHeaderAndCache(originRangeStart, cacheFileSize - 1, cacheFileSize, audioCache);
            // 如果缓存不足,返回Response Content(处理缓存不足的情况)
            if (realResponse == null) {
                Log.d(LOG_TAG, "缓存不足,发送请求");
                realResponse = HttpUtils.send(request);
                if (realResponse == null) {
                    return;
                }
            }
            Log.d(LOG_TAG, "接收ResponseContent");
            InputStream data = realResponse.getInputStream();
            if (!isCacheEnough) {
                byte[] buff = new byte[1024 * 40];
                boolean isPrint = true;
                int fileLength = 0;
                int readBytes;
                while (Thread.currentThread() == MediaPlayerProxy.downloadThread && (readBytes = data.read(buff, 0, buff.length)) != -1) {
                    long fileBufferLocation = fileLength + realRangeStart;
                    fileLength += readBytes;
                    long fileBufferEndLocation = fileLength + realRangeStart;
                    // 保存文件
                    if (fileUtils.getLength() == fileBufferLocation) {
                        fileUtils.write(buff, readBytes);
                    }
                    // 打印缓存大小
                    if (System.currentTimeMillis() / 1000 % 2 == 0) {
                        if (isPrint) {
                            Log.d(LOG_TAG, "Cache Size:" + readBytes + " File Start:" + fileBufferLocation + "File End:" + fileBufferEndLocation);
                            isPrint = false;
                        }
                    } else {
                        isPrint = true;
                    }
                    client.getOutputStream().write(buff, 0, readBytes);
                }
            }
        }
    } catch (SocketException e) {
        Log.i(LOG_TAG, "连接被终止", e);
    } catch (Exception e) {
        Log.e(LOG_TAG, e.getMessage(), e);
    } finally {
        client.close();
        Log.i(LOG_TAG, "代理关闭");
    }
}
Also used : SocketException(java.net.SocketException) HttpURLConnection(java.net.HttpURLConnection) InputStream(java.io.InputStream) SocketException(java.net.SocketException) URISyntaxException(java.net.URISyntaxException) IOException(java.io.IOException)

Example 87 with SocketException

use of java.net.SocketException in project GT by Tencent.

the class GTCaptureActivity method startTcpDump.

// 最后调整实际的文件名和参数
private void startTcpDump(String filePath) {
    String realParam = param;
    // 如果是wifi,则适配为wlan0,对应小米等手机,其实大部分机型可用网卡名都是wlan0
    if (NetUtils.isWifiActive()) {
        try {
            NetworkInterface network = NetworkInterface.getByName("wlan0");
            if (network != null && !param.contains("wlan0")) {
                realParam = "-i wlan0 " + param;
            }
        } catch (SocketException e) {
        // nothing should do
        }
    }
    GTCaptureEngine.getInstance().doCapture(filePath + "_" + String.valueOf(count) + ".pcap", realParam);
}
Also used : SocketException(java.net.SocketException) NetworkInterface(java.net.NetworkInterface)

Example 88 with SocketException

use of java.net.SocketException in project eureka by Netflix.

the class SystemUtil method getServerIPv4.

/**
     * Returns server IP address (v4 or v6) bound to local NIC. If multiple NICs are present, choose 'eth0' or 'en0' or
     * any one with name ending with 0. If non found, take first on the list that is not localhost. If no NIC
     * present (relevant only for desktop deployments), return loopback address.
     */
public static String getServerIPv4() {
    String candidateAddress = null;
    try {
        Enumeration<NetworkInterface> nics = NetworkInterface.getNetworkInterfaces();
        while (nics.hasMoreElements()) {
            NetworkInterface nic = nics.nextElement();
            Enumeration<InetAddress> inetAddresses = nic.getInetAddresses();
            while (inetAddresses.hasMoreElements()) {
                String address = inetAddresses.nextElement().getHostAddress();
                String nicName = nic.getName();
                if (nicName.startsWith("eth0") || nicName.startsWith("en0")) {
                    return address;
                }
                if (nicName.endsWith("0") || candidateAddress == null) {
                    candidateAddress = address;
                }
            }
        }
    } catch (SocketException e) {
        throw new RuntimeException("Cannot resolve local network address", e);
    }
    return candidateAddress == null ? "127.0.0.1" : candidateAddress;
}
Also used : SocketException(java.net.SocketException) NetworkInterface(java.net.NetworkInterface) InetAddress(java.net.InetAddress)

Example 89 with SocketException

use of java.net.SocketException in project ribbon by Netflix.

the class HelloUdpServerExternalResource method start.

public void start() {
    int port;
    try {
        port = choosePort();
    } catch (SocketException e) {
        throw new RuntimeException("Error choosing point", e);
    }
    server = RxNetty.createUdpServer(port, new ConnectionHandler<DatagramPacket, DatagramPacket>() {

        @Override
        public Observable<Void> handle(final ObservableConnection<DatagramPacket, DatagramPacket> newConnection) {
            return newConnection.getInput().flatMap(new Func1<DatagramPacket, Observable<Void>>() {

                @Override
                public Observable<Void> call(final DatagramPacket received) {
                    return Observable.interval(timeout, TimeUnit.MILLISECONDS).take(1).flatMap(new Func1<Long, Observable<Void>>() {

                        @Override
                        public Observable<Void> call(Long aLong) {
                            InetSocketAddress sender = received.sender();
                            LOG.info("Received datagram. Sender: " + sender);
                            ByteBuf data = newConnection.getChannel().alloc().buffer(WELCOME_MSG_BYTES.length);
                            data.writeBytes(WELCOME_MSG_BYTES);
                            return newConnection.writeAndFlush(new DatagramPacket(data, sender));
                        }
                    });
                }
            });
        }
    });
    server.start();
    LOG.info("UDP hello server started at port: " + port);
}
Also used : SocketException(java.net.SocketException) ObservableConnection(io.reactivex.netty.channel.ObservableConnection) InetSocketAddress(java.net.InetSocketAddress) ByteBuf(io.netty.buffer.ByteBuf) Observable(rx.Observable) ConnectionHandler(io.reactivex.netty.channel.ConnectionHandler) DatagramPacket(io.netty.channel.socket.DatagramPacket) Func1(rx.functions.Func1)

Example 90 with SocketException

use of java.net.SocketException in project sonarqube by SonarSource.

the class DefaultHttpDownloaderTest method openStream_network_errors.

@Test(timeout = 10000)
public void openStream_network_errors() throws IOException, URISyntaxException {
    // non routable address
    String url = "http://10.255.255.1";
    thrown.expect(SonarException.class);
    thrown.expect(hasCause(new BaseMatcher<Exception>() {

        @Override
        public boolean matches(Object ex) {
            return // Java 8
            ex instanceof NoRouteToHostException || ex instanceof SocketException || // Java 7 or before
            ex instanceof SocketTimeoutException;
        }

        @Override
        public void describeTo(Description arg0) {
        }
    }));
    DefaultHttpDownloader downloader = new DefaultHttpDownloader(new MapSettings(), 10, 50000);
    downloader.openStream(new URI(url));
}
Also used : SocketException(java.net.SocketException) SocketTimeoutException(java.net.SocketTimeoutException) Description(org.hamcrest.Description) BaseMatcher(org.hamcrest.BaseMatcher) MapSettings(org.sonar.api.config.MapSettings) NoRouteToHostException(java.net.NoRouteToHostException) URI(java.net.URI) Test(org.junit.Test)

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