java.net.Socket Java Examples
The following examples show how to use
java.net.Socket.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ShutdownInput.java From jdk8u-jdk with GNU General Public License v2.0 | 6 votes |
public static void test(Socket s1, Socket s2, String mesg) throws Exception { OutputStream os = s1.getOutputStream(); os.write("This is a message".getBytes("US-ASCII")); InputStream in = s2.getInputStream(); s2.shutdownInput(); if (in.available() != 0) { failed = true; System.out.println(mesg + ":" + s2 + " in.available() should be 0, " + "but returns "+ in.available()); } byte[] ba = new byte[2]; if (in.read() != -1 || in.read(ba) != -1 || in.read(ba, 0, ba.length) != -1) { failed = true; System.out.append(mesg + ":" + s2 + " in.read() should be -1"); } }
Example #2
Source File: DFSOutputStream.java From big-c with Apache License 2.0 | 6 votes |
/** * Create a socket for a write pipeline * @param first the first datanode * @param length the pipeline length * @param client client * @return the socket connected to the first datanode */ static Socket createSocketForPipeline(final DatanodeInfo first, final int length, final DFSClient client) throws IOException { final String dnAddr = first.getXferAddr( client.getConf().connectToDnViaHostname); if (DFSClient.LOG.isDebugEnabled()) { DFSClient.LOG.debug("Connecting to datanode " + dnAddr); } final InetSocketAddress isa = NetUtils.createSocketAddr(dnAddr); final Socket sock = client.socketFactory.createSocket(); final int timeout = client.getDatanodeReadTimeout(length); NetUtils.connect(sock, isa, client.getRandomLocalInterfaceAddr(), client.getConf().socketTimeout); sock.setSoTimeout(timeout); sock.setSendBufferSize(HdfsConstants.DEFAULT_DATA_SOCKET_SIZE); if(DFSClient.LOG.isDebugEnabled()) { DFSClient.LOG.debug("Send buf size " + sock.getSendBufferSize()); } return sock; }
Example #3
Source File: JavaDebugServer.java From java-debug with Eclipse Public License 1.0 | 6 votes |
private Runnable createConnectionTask(Socket connection) { return new Runnable() { @Override public void run() { try { ProtocolServer protocolServer = new ProtocolServer(connection.getInputStream(), connection.getOutputStream(), JdtProviderContextFactory.createProviderContext()); // protocol server will dispatch request and send response in a while-loop. protocolServer.run(); } catch (IOException e) { logger.log(Level.SEVERE, String.format("Socket connection exception: %s", e.toString()), e); } finally { logger.info("Debug connection closed"); } } }; }
Example #4
Source File: TestBlockReplacement.java From RDFS with Apache License 2.0 | 6 votes |
private boolean replaceBlock( Block block, DatanodeInfo source, DatanodeInfo sourceProxy, DatanodeInfo destination, int namespaceId) throws IOException { Socket sock = new Socket(); sock.connect(NetUtils.createSocketAddr( destination.getName()), HdfsConstants.READ_TIMEOUT); sock.setKeepAlive(true); // sendRequest DataOutputStream out = new DataOutputStream(sock.getOutputStream()); out.writeShort(DataTransferProtocol.DATA_TRANSFER_VERSION); out.writeByte(DataTransferProtocol.OP_REPLACE_BLOCK); out.writeInt(namespaceId); out.writeLong(block.getBlockId()); out.writeLong(block.getGenerationStamp()); Text.writeString(out, source.getStorageID()); sourceProxy.write(out); out.flush(); // receiveResponse DataInputStream reply = new DataInputStream(sock.getInputStream()); short status = reply.readShort(); if(status == DataTransferProtocol.OP_STATUS_SUCCESS) { return true; } return false; }
Example #5
Source File: SSLSecurity.java From openjdk-8-source with GNU General Public License v2.0 | 6 votes |
public String chooseClientAlias(String[] keyTypes, Principal[] issuers, Socket socket) { String retval; if (keyTypes == null) { return null; } /* * Scan the list, look for something we can pass back. */ for (int i = 0; i < keyTypes.length; i++) { if ((retval = theX509KeyManager.chooseClientAlias(keyTypes[i], issuers)) != null) return retval; } return null; }
Example #6
Source File: TcpClient.java From Lamp with BSD 3-Clause "New" or "Revised" License | 6 votes |
@Override public void run() { try { Socket socket = new Socket(hostIP, port); transceiver = new SocketTransceiver(socket) { @Override public void onReceive(InetAddress addr, String s) { TcpClient.this.onReceive(this, s); } @Override public void onDisconnect(InetAddress addr) { connect = false; TcpClient.this.onDisconnect(this); } }; transceiver.start(); connect = true; this.onConnect(transceiver); } catch (Exception e) { e.printStackTrace(); this.onConnectFailed(); } }
Example #7
Source File: TcpSocketManager.java From logging-log4j2 with Apache License 2.0 | 6 votes |
@Override protected synchronized boolean closeOutputStream() { final boolean closed = super.closeOutputStream(); if (reconnector != null) { reconnector.shutdown(); reconnector.interrupt(); reconnector = null; } final Socket oldSocket = socket; socket = null; if (oldSocket != null) { try { oldSocket.close(); } catch (final IOException e) { LOGGER.error("Could not close socket {}", socket); return false; } } return closed; }
Example #8
Source File: SocketClient.java From app_process-shell-use with MIT License | 6 votes |
public SocketClient(String commod, onServiceSend onServiceSend) { cmd = commod; mOnServiceSend = onServiceSend; try { Log.d(TAG, "与service进行socket通讯,地址=" + HOST + ":" + port); /** 创建Socket*/ // 创建一个流套接字并将其连接到指定 IP 地址的指定端口号(本处是本机) Socket socket = new Socket(); socket.connect(new InetSocketAddress(HOST, port), 3000);//设置连接请求超时时间3 s // 接收3s超时 socket.setSoTimeout(3000); Log.d(TAG, "与service进行socket通讯,超时为:" + 3000); /** 发送客户端准备传输的信息 */ // 由Socket对象得到输出流,并构造PrintWriter对象 printWriter = new PrintWriter(socket.getOutputStream(), true); /** 用于获取服务端传输来的信息 */ // 由Socket对象得到输入流,并构造相应的BufferedReader对象 bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream())); new CreateServerThread(socket); send(cmd); } catch (Exception e) { e.printStackTrace(); Log.d(TAG, "与service进行socket通讯发生错误" + e); mOnServiceSend.getSend("###ShellRunError:" + e.toString()); } }
Example #9
Source File: DefaultSocketChannelConfig.java From netty4.0.27Learn with Apache License 2.0 | 6 votes |
/** * Creates a new instance. */ public DefaultSocketChannelConfig(SocketChannel channel, Socket javaSocket) { super(channel); if (javaSocket == null) { throw new NullPointerException("javaSocket"); } this.javaSocket = javaSocket; // Enable TCP_NODELAY by default if possible. if (PlatformDependent.canEnableTcpNoDelayByDefault()) { try { setTcpNoDelay(true); } catch (Exception e) { // Ignore. } } }
Example #10
Source File: RpcSocketInputStream.java From p4ic4idea with Apache License 2.0 | 6 votes |
/** * Construct a suitable stream for the passed-in socket. No assumptions * are made about the passed-in socket except that a) it's not null, and * b) it's been initialized and set up for reading (or at least the successful * retrieval of a suitable input stream) by the caller. * * @param socket non-null socket */ public RpcSocketInputStream(Socket socket, ServerStats stats) { super(); if (socket == null) { throw new NullPointerError( "null RPC socket passed to RpcSocketInputStream constructor"); } this.socket = socket; this.stats = stats; try { this.socketStream = socket.getInputStream(); } catch (IOException ioexc) { Log.error("Unexpected I/O exception thrown during input stream retrieval" + " in RpcSocketInputStream constructor: " + ioexc.getLocalizedMessage()); Log.exception(ioexc); throw new P4JavaError( "Unexpected I/O exception thrown during input stream retrieval" + " in RpcSocketInputStream constructor: " + ioexc.getLocalizedMessage()); } }
Example #11
Source File: MockingUtils.java From gameserver with Apache License 2.0 | 6 votes |
static SocketFactory mockSocketFactory(OutputStream out, InputStream in) { try { Socket socket = mock(Socket.class); when(socket.getOutputStream()).thenReturn(out); when(socket.getInputStream()).thenReturn(in); SocketFactory factory = mock(SocketFactory.class); when(factory.createSocket()).thenReturn(socket); when(factory.createSocket(anyString(), anyInt())).thenReturn(socket); return factory; } catch (Exception e) { e.printStackTrace(); throw new AssertionError("Cannot be here!"); } }
Example #12
Source File: Client.java From jblink with BSD 3-Clause "New" or "Revised" License | 6 votes |
/** Creates a client that will connect to the specified address. It will map messages as defined by the specified object model. @param addr an server address on the form 'host:port' @param om an object model @throws BlinkException if there is a schema or binding problem @throws IOException if there is a socket problem */ public Client (String addr, ObjectModel om) throws BlinkException, IOException { String [] parts = addr.split (":"); if (parts.length != 2) throw new IllegalArgumentException ( "Address must be on the form 'host:port'"); this.sock = new Socket (parts [0], Integer.parseInt (parts [1])); this.om = om; this.oreg = new DefaultObsRegistry (om); this.os = sock.getOutputStream (); this.wr = new CompactWriter (om, os); this.udpsock = null; this.bs = null; }
Example #13
Source File: TestApplication.java From jdk8u-jdk with GNU General Public License v2.0 | 5 votes |
public static void main(String[] args) throws IOException { // Some tests require the application to exit immediately if (args.length > 0 && args[0].equals("-exit")) { return; } // bind to a random port ServerSocket ss = new ServerSocket(0); int port = ss.getLocalPort(); int pid = -1; try { pid = ProcessTools.getProcessId(); } catch (Exception e) { e.printStackTrace(); } // signal test that we are started - do not remove these lines!! System.out.println("port:" + port); System.out.println("pid:" + pid); System.out.println("waiting for the manager ..."); System.out.flush(); // wait for manager to connect Socket s = ss.accept(); s.close(); ss.close(); }
Example #14
Source File: ObservableServerSocketTest.java From rxjava-extras with Apache License 2.0 | 5 votes |
@Test public void testAcceptSocketRejectsAlways() throws UnknownHostException, IOException, InterruptedException { reset(); TestSubscriber<Object> ts = TestSubscriber.create(); try { int bufferSize = 4; AtomicInteger port = new AtomicInteger(); IO.serverSocketAutoAllocatePort(Actions.setAtomic(port)) // .readTimeoutMs(10000) // .acceptTimeoutMs(200) // .bufferSize(bufferSize) // .acceptSocketIf(Functions.alwaysFalse()) // .create() // .subscribeOn(scheduler) // .subscribe(ts); Thread.sleep(300); Socket socket = new Socket("localhost", port.get()); OutputStream out = socket.getOutputStream(); out.write("12345678901234567890".getBytes()); out.close(); socket.close(); Thread.sleep(1000); ts.assertNoValues(); } finally { // will close server socket ts.unsubscribe(); } }
Example #15
Source File: MasterTest.java From TUM_Homework with GNU General Public License v3.0 | 5 votes |
private void runInitStores() throws IOException { Master.initStores(2, new ServerSocket() { @Override public Socket accept() throws IOException { return new Socket(); } }); }
Example #16
Source File: ProtoCommon.java From fastdfs-spring-boot-starter with GNU Lesser General Public License v3.0 | 5 votes |
/** * send quit command to server and close socket * * @param sock the Socket object */ public static void closeSocket(Socket sock) throws IOException { byte[] header; header = packHeader(FDFS_PROTO_CMD_QUIT, 0, (byte) 0); sock.getOutputStream().write(header); sock.close(); }
Example #17
Source File: BkSafe.java From takes with MIT License | 5 votes |
/** * Ctor. * @param back Original back */ public BkSafe(final Back back) { super(new Back() { @Override @SuppressWarnings("PMD.AvoidCatchingThrowable") public void accept(final Socket socket) { try { back.accept(socket); // @checkstyle IllegalCatchCheck (1 line) } catch (final Throwable ignored) { } } }); }
Example #18
Source File: SSLKeyManager.java From PADListener with GNU General Public License v2.0 | 5 votes |
public synchronized String chooseServerAlias(String keyType, Principal[] issuers, Socket socket) { if (_preferredKeyManager != null) return _preferredKeyManager.chooseServerAlias(keyType, issuers, socket); Iterator<String> it = _managers.keySet().iterator(); while (it.hasNext()) { String source = it.next(); X509KeyManager km = _managers.get(source); String alias = km.chooseServerAlias(keyType, issuers, socket); if (alias != null) return source + SEP + alias; } return null; }
Example #19
Source File: SETrustingManager.java From BiglyBT with GNU General Public License v2.0 | 5 votes |
@Override public void checkClientTrusted(X509Certificate[] chain, String authType, Socket socket) throws CertificateException { if (delegate != null) { delegate.checkClientTrusted(chain, authType); } }
Example #20
Source File: SshTtyTestBase.java From termd with Apache License 2.0 | 5 votes |
@Override protected void assertDisconnect(boolean clean) throws Exception { if (clean) { session.disconnect(); } else { Field socketField = session.getClass().getDeclaredField("socket"); socketField.setAccessible(true); Socket socket = (Socket) socketField.get(session); socket.close(); } }
Example #21
Source File: ByteServer.java From dragonwell8_jdk with GNU General Public License v2.0 | 5 votes |
void closeConnection() throws IOException { Socket s = this.s; if (s != null) { this.s = null; s.close(); } }
Example #22
Source File: ProxySocketFactory.java From bisq with GNU Affero General Public License v3.0 | 5 votes |
@Override public Socket createSocket(InetAddress ia, int i, InetAddress localAddress, int localPort) throws IOException { Socket socket = new Socket(proxy); socket.bind(new InetSocketAddress(localAddress, localPort)); socket.connect(new InetSocketAddress(ia, i)); return socket; }
Example #23
Source File: StandardSocketFactory.java From big-c with Apache License 2.0 | 5 votes |
@Override public Socket createSocket(String host, int port) throws IOException, UnknownHostException { Socket socket = createSocket(); socket.connect(new InetSocketAddress(host, port)); return socket; }
Example #24
Source File: ApnsConnectionImpl.java From gameserver with Apache License 2.0 | 5 votes |
public synchronized void sendMessage(ApnsNotification m) throws NetworkIOException { int attempts = 0; while (true) { try { attempts++; Socket socket = socket(); socket.getOutputStream().write(m.marshall()); socket.getOutputStream().flush(); delegate.messageSent(m); logger.debug("Message \"{}\" sent", m); attempts = 0; break; } catch (Exception e) { if (attempts >= RETRIES) { logger.error("Couldn't send message " + m, e); delegate.messageSendFailed(m, e); Utilities.wrapAndThrowAsRuntimeException(e); } logger.warn("Failed to send message " + m + "... trying again", e); // The first failure might be due to closed connection // don't delay quite yet if (attempts != 1) Utilities.sleep(DELAY_IN_MS); Utilities.close(socket); socket = null; } } }
Example #25
Source File: FixedHostPortContainerTest.java From testcontainers-java with MIT License | 5 votes |
/** * Simple socket content reader from given container:port * * @param container to query * @param port to send request to * @return socket reader content * @throws IOException if any */ private String readResponse(GenericContainer container, Integer port) throws IOException { try ( final BufferedReader reader = Unreliables.retryUntilSuccess(10, TimeUnit.SECONDS, () -> { Uninterruptibles.sleepUninterruptibly(1, TimeUnit.SECONDS); final Socket socket = new Socket(container.getHost(), port); return new BufferedReader(new InputStreamReader(socket.getInputStream())); } ) ) { return reader.readLine(); } }
Example #26
Source File: Agent.java From dragonwell8_jdk with GNU General Public License v2.0 | 5 votes |
public static void agentmain(String args) throws IOException { System.out.println("Agent running..."); int port = Integer.parseInt(args); System.out.println("Agent connecting back to Tool...."); Socket s = new Socket(); s.connect( new InetSocketAddress(port) ); System.out.println("Agent connected to Tool."); s.close(); }
Example #27
Source File: HttpProxy.java From jdk8u60 with GNU General Public License v2.0 | 5 votes |
private void send200(Socket clientSocket) throws IOException { OutputStream out = clientSocket.getOutputStream(); PrintWriter pout = new PrintWriter(out); pout.println("HTTP/1.1 200 OK"); pout.println(); pout.flush(); }
Example #28
Source File: Agent.java From jdk8u_jdk with GNU General Public License v2.0 | 5 votes |
public static void agentmain(String args) throws IOException { System.out.println("Agent running..."); int port = Integer.parseInt(args); System.out.println("Agent connecting back to Tool...."); Socket s = new Socket(); s.connect( new InetSocketAddress(port) ); System.out.println("Agent connected to Tool."); s.close(); }
Example #29
Source File: TestManager.java From openjdk-jdk8u with GNU General Public License v2.0 | 5 votes |
public static void main(String[] args) throws Exception { String pid = args[0]; // pid as a string System.out.println("Starting TestManager for PID = " + pid); System.out.flush(); VirtualMachine vm = VirtualMachine.attach(pid); String agentPropLocalConnectorAddress = (String) vm.getAgentProperties().get(LOCAL_CONNECTOR_ADDRESS_PROP); int vmid = Integer.parseInt(pid); String jvmstatLocalConnectorAddress = ConnectorAddressLink.importFrom(vmid); if (agentPropLocalConnectorAddress == null && jvmstatLocalConnectorAddress == null) { // No JMX Connector address so attach to VM, and start local agent startManagementAgent(pid); agentPropLocalConnectorAddress = (String) vm.getAgentProperties().get(LOCAL_CONNECTOR_ADDRESS_PROP); jvmstatLocalConnectorAddress = ConnectorAddressLink.importFrom(vmid); } // Test address obtained from agent properties System.out.println("Testing the connector address from agent properties"); connect(pid, agentPropLocalConnectorAddress); // Test address obtained from jvmstat buffer System.out.println("Testing the connector address from jvmstat buffer"); connect(pid, jvmstatLocalConnectorAddress); // Shutdown application int port = Integer.parseInt(args[1]); System.out.println("Shutdown process via TCP port: " + port); Socket s = new Socket(); s.connect(new InetSocketAddress(port)); s.close(); }
Example #30
Source File: ClientGlobal.java From fastdfs-client-java with BSD 3-Clause "New" or "Revised" License | 5 votes |
/** * construct Socket object * * @param addr InetSocketAddress object, including ip address and port * @return connected Socket object */ public static Socket getSocket(InetSocketAddress addr) throws IOException { Socket sock = new Socket(); sock.setReuseAddress(true); sock.setSoTimeout(ClientGlobal.g_network_timeout); sock.connect(addr, ClientGlobal.g_connect_timeout); return sock; }