当前位置: 首页>>代码示例>>Java>>正文


Java Socket.close方法代码示例

本文整理汇总了Java中java.net.Socket.close方法的典型用法代码示例。如果您正苦于以下问题:Java Socket.close方法的具体用法?Java Socket.close怎么用?Java Socket.close使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在java.net.Socket的用法示例。


在下文中一共展示了Socket.close方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: SetReceiveBufferSize

import java.net.Socket; //导入方法依赖的package包/类
public SetReceiveBufferSize() throws Exception {
    ServerSocket ss = new ServerSocket(0);
    Socket s = new Socket("localhost", ss.getLocalPort());
    Socket accepted = ss.accept();
    try {
        s.setReceiveBufferSize(0);
    } catch (IllegalArgumentException e) {
        return;
    } catch (Exception ex) {
    } finally {
        ss.close();
        s.close();
        accepted.close();
    }
    throw new RuntimeException("IllegalArgumentException not thrown!");
}
 
开发者ID:AdoptOpenJDK,项目名称:openjdk-jdk10,代码行数:17,代码来源:SetReceiveBufferSize.java

示例2: shutdown

import java.net.Socket; //导入方法依赖的package包/类
/**
 * Force-closes this connection.
 * If the connection is still in the process of being open (the method
 * {@link #opening opening} was already called but
 * {@link #openCompleted openCompleted} was not), the associated
 * socket that is being connected to a remote address will be closed.
 * That will interrupt a thread that is blocked on connecting
 * the socket.
 * If the connection is not yet open, this will prevent the connection
 * from being opened.
 *
 * @throws IOException      in case of a problem
 */
@Override
public void shutdown() throws IOException {
    shutdown = true;
    try {
        super.shutdown();
        if (log.isDebugEnabled()) {
            log.debug("Connection " + this + " shut down");
        }
        Socket sock = this.socket; // copy volatile attribute
        if (sock != null)
            sock.close();
    } catch (IOException ex) {
        log.debug("I/O error shutting down connection", ex);
    }
}
 
开发者ID:lamsfoundation,项目名称:lams,代码行数:29,代码来源:DefaultClientConnection.java

示例3: testMaxLineLength

import java.net.Socket; //导入方法依赖的package包/类
/**
 * Test that line above MaxLineLength are discarded
 *
 * @throws InterruptedException
 * @throws IOException
 */
@Test
public void testMaxLineLength() throws InterruptedException, IOException {
  String encoding = "UTF-8";
  startSource(encoding, "false", "1", "10");
  Socket netcatSocket = new Socket(localhost, selectedPort);
  try {
    sendEvent(netcatSocket, "123456789", encoding);
    Assert.assertArrayEquals("Channel contained our event",
                             "123456789".getBytes(defaultCharset), getFlumeEvent());
    sendEvent(netcatSocket, english, encoding);
    Assert.assertEquals("Channel does not contain an event", null, getRawFlumeEvent());
  } finally {
    netcatSocket.close();
    stopSource();
  }
}
 
开发者ID:moueimei,项目名称:flume-release-1.7.0,代码行数:23,代码来源:TestNetcatSource.java

示例4: testAvoidLoopbackTcpSockets

import java.net.Socket; //导入方法依赖的package包/类
/**
 * Test that we can't accidentally connect back to the connecting socket due
 * to a quirk in the TCP spec.
 *
 * This is a regression test for HADOOP-6722.
 */
@Test
public void testAvoidLoopbackTcpSockets() throws Exception {
  Configuration conf = new Configuration();

  Socket socket = NetUtils.getDefaultSocketFactory(conf)
    .createSocket();
  socket.bind(new InetSocketAddress("127.0.0.1", 0));
  System.err.println("local address: " + socket.getLocalAddress());
  System.err.println("local port: " + socket.getLocalPort());
  try {
    NetUtils.connect(socket,
      new InetSocketAddress(socket.getLocalAddress(), socket.getLocalPort()),
      20000);
    socket.close();
    fail("Should not have connected");
  } catch (ConnectException ce) {
    System.err.println("Got exception: " + ce);
    assertTrue(ce.getMessage().contains("resulted in a loopback"));
  } catch (SocketException se) {
    // Some TCP stacks will actually throw their own Invalid argument exception
    // here. This is also OK.
    assertTrue(se.getMessage().contains("Invalid argument"));
  }
}
 
开发者ID:naver,项目名称:hadoop,代码行数:31,代码来源:TestNetUtils.java

示例5: checkForTrigger

import java.net.Socket; //导入方法依赖的package包/类
private void checkForTrigger() {
    String msg_received;
    while(true){
        try{
            ServerSocket socket=new ServerSocket(serverPort);
            Socket clientSocket=socket.accept();
            DataInputStream DIS = new DataInputStream(clientSocket.getInputStream());
            msg_received = DIS.readUTF();
            clientSocket.close();
            socket.close();
        }
        catch(IOException e){
            msg_received=e.toString();
        }
        if(msg_received.equals("transmit_data")){

            Log.d("harsimarSingh","triggered");
            cameraView.captureImage();
        }}
}
 
开发者ID:simarsingh24,项目名称:TensorFlowDetector-App,代码行数:21,代码来源:MainActivity.java

示例6: closeSocket

import java.net.Socket; //导入方法依赖的package包/类
private void closeSocket(Socket socket) {
    try {
        socket.close();
    } catch (IOException e) {
        // Ignore
    }
}
 
开发者ID:liaokailin,项目名称:tomcat7,代码行数:8,代码来源:JIoEndpoint.java

示例7: read

import java.net.Socket; //导入方法依赖的package包/类
private void read() throws IOException {
    metrics.clear();
    Socket socket = serverSocket.accept();
    try {
        socket.setSoTimeout(socketTimeoutMillis);
        socket.setKeepAlive(false);
        BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        String line;
        while ((line = reader.readLine()) != null) {
            int updatedSeconds = (int) (TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis()));
            Metric metric = metricFactory.createMetric(line, updatedSeconds);
            if (metric != null) {
                metrics.add(metric);
                if (metrics.size() >= readBatchSize) {
                    metricCacher.submitMetrics(metrics);
                    metrics.clear();
                }
            }
        }
    } catch (SocketTimeoutException e) {
        log.warn("Socket timeout from " + socket.getRemoteSocketAddress().toString());
    } finally {
        socket.close();
    }
    metricCacher.submitMetrics(metrics);
    metrics.clear();
}
 
开发者ID:yandex,项目名称:graphouse,代码行数:28,代码来源:MetricServer.java

示例8: closeSocket

import java.net.Socket; //导入方法依赖的package包/类
private void closeSocket(Socket sock) {
   try {
      sock.close();
   }
   catch (Exception e) {
      // we cannot do anything if this op crashes
   }
}
 
开发者ID:convertigo,项目名称:convertigo-eclipse,代码行数:9,代码来源:HttpProxyWorker.java

示例9: respond

import java.net.Socket; //导入方法依赖的package包/类
public void respond(Socket socket, Object[] params) throws IOException {

		String content = methodResponse(params);
		String response = RESPONSE + (content.length()) + NEWLINES + content;
		OutputStream outputStream = socket.getOutputStream();
		outputStream.write(response.getBytes());
		outputStream.flush();
		outputStream.close();
		socket.close();
		Log.d(Tag.LOG, "response:" + response);
	}
 
开发者ID:archos-sa,项目名称:aos-MediaLib,代码行数:12,代码来源:XMLRPCServer.java

示例10: process

import java.net.Socket; //导入方法依赖的package包/类
@Override
public void process(Config config, String stateLine, Socket socket) {
    try {
        socket.close();
    } catch (Exception e) {
    }
}
 
开发者ID:android-notes,项目名称:vase,代码行数:8,代码来源:NotSupport.java

示例11: main

import java.net.Socket; //导入方法依赖的package包/类
public static void main(String args[]) throws Exception {

        if (args.length != 1) {
            throw new RuntimeException("Usage: ShutdownSimpleApplication" +
                " port-file");
        }

        // read the (TCP) port number from the given file

        File f = new File(args[0]);
        FileInputStream fis = new FileInputStream(f);
        byte b[] = new byte[8];
        int n = fis.read(b);
        if (n < 1) {
            throw new RuntimeException("Empty port-file");
        }
        fis.close();

        String str = new String(b, 0, n, "UTF-8");
        System.out.println("INFO: Port number of SimpleApplication: " + str);
        int port = Integer.parseInt(str);

        // Now connect to the port (which will shutdown application)

        System.out.println("INFO: Connecting to port " + port +
            " to shutdown SimpleApplication ...");
        System.out.flush();

        Socket s = new Socket();
        s.connect( new InetSocketAddress(port) );
        s.close();

        System.out.println("INFO: done connecting to SimpleApplication.");
        System.out.flush();

        System.exit(0);
    }
 
开发者ID:lambdalab-mirror,项目名称:jdk8u-jdk,代码行数:38,代码来源:ShutdownSimpleApplication.java

示例12: tryToClose

import java.net.Socket; //导入方法依赖的package包/类
private void tryToClose(@Nullable Socket s) {
	try {
		if (s != null) s.close();
	} catch (IOException e) {
		if (LOG.isLoggable(WARNING)) LOG.log(WARNING, e.toString(), e);
	}
}
 
开发者ID:rafjordao,项目名称:Nird2,代码行数:8,代码来源:TorPlugin.java

示例13: handleClientInitialisationError

import java.net.Socket; //导入方法依赖的package包/类
private void handleClientInitialisationError(final Socket clientSocket, final IOException e) {
    final String addr = clientSocket.getRemoteSocketAddress().toString();
    admin.unexpectedEvent(String.format(
            "Can't initialize connection of client '%s' correctly. Closing the connection to it.", addr), e);
    try {
        clientSocket.close();
    } catch (IOException e1) {
        admin.unexpectedEvent(String.format("Could not close the connection to the client '%s'.", addr), e1);
    }

}
 
开发者ID:rbi,项目名称:trading4j,代码行数:12,代码来源:OioServer.java

示例14: testIncomingConnection

import java.net.Socket; //导入方法依赖的package包/类
@Test
public void testIncomingConnection() throws Exception {
	if (!systemHasLocalIpv4Address()) {
		System.err.println("WARNING: Skipping test, no local IPv4 address");
		return;
	}
	Callback callback = new Callback();
	Executor executor = Executors.newCachedThreadPool();
	DuplexPlugin plugin = new LanTcpPlugin(executor, backoff, callback,
			0, 0);
	plugin.start();
	// The plugin should have bound a socket and stored the port number
	assertTrue(callback.propertiesLatch.await(5, SECONDS));
	String ipPorts = callback.local.get("ipPorts");
	assertNotNull(ipPorts);
	String[] split = ipPorts.split(",");
	assertEquals(1, split.length);
	split = split[0].split(":");
	assertEquals(2, split.length);
	String addrString = split[0], portString = split[1];
	InetAddress addr = InetAddress.getByName(addrString);
	assertTrue(addr instanceof Inet4Address);
	assertFalse(addr.isLoopbackAddress());
	assertTrue(addr.isLinkLocalAddress() || addr.isSiteLocalAddress());
	int port = Integer.parseInt(portString);
	assertTrue(port > 0 && port < 65536);
	// The plugin should be listening on the port
	InetSocketAddress socketAddr = new InetSocketAddress(addr, port);
	Socket s = new Socket();
	s.connect(socketAddr, 100);
	assertTrue(callback.connectionsLatch.await(5, SECONDS));
	s.close();
	// Stop the plugin
	plugin.stop();
}
 
开发者ID:rafjordao,项目名称:Nird2,代码行数:36,代码来源:LanTcpPluginTest.java

示例15: closeSocket

import java.net.Socket; //导入方法依赖的package包/类
/**
 * Closes the socket ignoring {@link IOException}
 *
 * @param sock the Socket to close
 */
public static void closeSocket(Socket sock) {
  if (sock != null) {
    try {
      sock.close();
    } catch (IOException ignored) {
    }
  }
}
 
开发者ID:naver,项目名称:hadoop,代码行数:14,代码来源:IOUtils.java


注:本文中的java.net.Socket.close方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。