java.net.Socket.getInputStream()方法的使用及代码示例

x33g5p2x  于2022-01-29 转载在 其他  
字(9.5k)|赞(0)|评价(0)|浏览(429)

本文整理了Java中java.net.Socket.getInputStream()方法的一些代码示例,展示了Socket.getInputStream()的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。Socket.getInputStream()方法的具体详情如下:
包路径:java.net.Socket
类名称:Socket
方法名:getInputStream

Socket.getInputStream介绍

[英]Returns an input stream to read data from this socket.
[中]返回从该套接字读取数据的输入流。

代码示例

代码示例来源:origin: iluwatar/java-design-patterns

@Override
public void run() {
 try (Socket socket = new Socket(InetAddress.getLocalHost(), serverPort)) {
  OutputStream outputStream = socket.getOutputStream();
  PrintWriter writer = new PrintWriter(outputStream);
  sendLogRequests(writer, socket.getInputStream());
 } catch (IOException e) {
  LOGGER.error("error sending requests", e);
  throw new RuntimeException(e);
 }
}

代码示例来源:origin: alibaba/canal

BioSocketChannel(Socket socket) throws IOException{
  this.socket = socket;
  this.input = new BufferedInputStream(socket.getInputStream(), 16384);
  this.output = socket.getOutputStream();
}

代码示例来源:origin: facebook/stetho

private IRCClientConnection(
  StethoReporter reporter,
  Socket socket,
  String charset)
  throws IOException {
 mReporter = reporter;
 mSocket = socket;
 mInput = new BufferedReader(new InputStreamReader(socket.getInputStream(), charset));
 mOutput = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(), charset));
}

代码示例来源:origin: stanfordnlp/CoreNLP

/**
 * Returs a Tree from the server connected to at host:port.
 */
public Tree getTree(String query) 
 throws IOException
{
 Socket socket = new Socket(host, port);
 Writer out = new OutputStreamWriter(socket.getOutputStream(), "utf-8");
 out.write("tree " + query + "\n");
 out.flush();
 ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
 Object o;
 try {
  o = ois.readObject();
 } catch (ClassNotFoundException e) {
  throw new RuntimeException(e);
 }
 if (!(o instanceof Tree)) {
  throw new IllegalArgumentException("Expected a tree");
 }
 Tree tree = (Tree) o;
 socket.close();
 return tree;
}

代码示例来源:origin: stackoverflow.com

ServerSocket serverSocket = new ServerSocket(4444);
Socket clientSocket = serverSocket.accept();
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
while (true) {
 out.println("output");
 if (out.checkError()) System.out.println("ERROR writing data to socket !!!");
 System.out.println(clientSocket.isConnected());
 System.out.println(clientSocket.getInputStream().read());
    // thread sleep ...
 // break condition , close sockets and the like ...
}

代码示例来源:origin: stackoverflow.com

try {
  Socket x = new Socket("1.1.1.1", 6789);
  x.getInputStream().read()
} catch (IOException e) {
  System.err.println("Connection could not be established, please try again later!")
}

代码示例来源:origin: jenkinsci/jenkins

public boolean connect(Socket socket) throws IOException {
    try {
      LOGGER.log(Level.FINE, "Requesting ping from {0}", socket.getRemoteSocketAddress());
      try (DataOutputStream out = new DataOutputStream(socket.getOutputStream())) {
        out.writeUTF("Protocol:Ping");
        try (InputStream in = socket.getInputStream()) {
          byte[] response = new byte[ping.length];
          int responseLength = in.read(response);
          if (responseLength == ping.length && Arrays.equals(response, ping)) {
            LOGGER.log(Level.FINE, "Received ping response from {0}", socket.getRemoteSocketAddress());
            return true;
          } else {
            LOGGER.log(Level.FINE, "Expected ping response from {0} of {1} got {2}", new Object[]{
                socket.getRemoteSocketAddress(),
                new String(ping, "UTF-8"),
                responseLength > 0 && responseLength <= response.length ?
                  new String(response, 0, responseLength, "UTF-8") :
                  "bad response length " + responseLength
            });
            return false;
          }
        }
      }
    } finally {
      socket.close();
    }
  }
}

代码示例来源:origin: stackoverflow.com

public void gracefulDisconnect(Socket sok) {
  InputStream is = sok.getInputStream();
  sok.shutdownOutput(); // Sends the 'FIN' on the network
  while (is.read() >= 0) ; // "read()" returns '-1' when the 'FIN' is reached
  sok.close(); // Now we can close the Socket
}

代码示例来源:origin: igniterealtime/Smack

HttpRequestHandler(Socket socket) throws Exception {
  this.socket = socket;
  this.input = socket.getInputStream();
  this.output = socket.getOutputStream();
  this.br = new BufferedReader(new InputStreamReader(socket.getInputStream(), StringUtils.UTF8));
}

代码示例来源:origin: apache/zookeeper

public static void kill(String host, int port) {
  Socket s = null;
  try {
    byte[] reqBytes = new byte[4];
    ByteBuffer req = ByteBuffer.wrap(reqBytes);
    req.putInt(ByteBuffer.wrap("kill".getBytes()).getInt());
    s = new Socket();
    s.setSoLinger(false, 10);
    s.setSoTimeout(20000);
    s.connect(new InetSocketAddress(host, port));
    InputStream is = s.getInputStream();
    OutputStream os = s.getOutputStream();
    os.write(reqBytes);
    byte[] resBytes = new byte[4];
    int rc = is.read(resBytes);
    String retv = new String(resBytes);
    System.out.println("rc=" + rc + " retv=" + retv);
  } catch (IOException e) {
    LOG.warn("Unexpected exception", e);
  } finally {
    if (s != null) {
      try {
        s.close();
      } catch (IOException e) {
        LOG.warn("Unexpected exception", e);
      }
    }
  }
}

代码示例来源:origin: frohoff/ysoserial

public static Channel openChannel ( InetSocketAddress isa ) throws IOException, SocketException {
    System.err.println("* Opening socket " + isa);
    Socket s = SocketFactory.getDefault().createSocket(isa.getAddress(), isa.getPort());
    s.setKeepAlive(true);
    s.setTcpNoDelay(true);
  
    System.err.println("* Opening channel");
    OutputStream outputStream = s.getOutputStream();
    DataOutputStream dos = new DataOutputStream(outputStream);
    dos.writeUTF("Protocol:CLI-connect");
    ExecutorService cp = Executors.newCachedThreadPool(new ThreadFactory() {
  
      public Thread newThread ( Runnable r ) {
        Thread t = new Thread(r, "Channel");
        t.setDaemon(true);
        return t;
      }
    });
    Channel c = new ChannelBuilder("EXPLOIT", cp).withMode(Mode.BINARY).build(s.getInputStream(), outputStream);
    System.err.println("* Channel open");
    return c;
  }
}

代码示例来源:origin: jenkinsci/jenkins

Writer o = new OutputStreamWriter(s.getOutputStream(), "UTF-8");
  InputStream i = s.getInputStream();
  IOUtils.copy(i, new NullOutputStream());
  s.shutdownInput();
} finally {
  s.close();

代码示例来源:origin: jMonkeyEngine/jmonkeyengine

public SocketConnector( InetAddress address, int port ) throws IOException
{
  this.sock = new Socket(address, port);
  remoteAddress = sock.getRemoteSocketAddress(); // for info purposes 
  
  // Disable Nagle's buffering so data goes out when we
  // put it there.
  sock.setTcpNoDelay(true);
  
  in = sock.getInputStream();
  out = sock.getOutputStream();
  
  connected.set(true);
}

代码示例来源:origin: stackoverflow.com

String msg_received;

ServerSocket socket = new ServerSocket(1755);
Socket clientSocket = socket.accept();       //This is blocking. It will wait.
DataInputStream DIS = new DataInputStream(clientSocket.getInputStream());
msg_received = DIS.readUTF();
clientSocket.close();
socket.close();

代码示例来源:origin: redisson/redisson

public TCPObjectSocket( Socket socket, FSTConfiguration conf) throws IOException {
    this.socket = socket;
//        socket.setSoLinger(true,0);
    this.out = new BufferedOutputStream(socket.getOutputStream(), BUFFER_SIZE);
    this.in  = new BufferedInputStream(socket.getInputStream(), BUFFER_SIZE);
    this.conf = conf;
  }

代码示例来源:origin: stanfordnlp/CoreNLP

private Session(Socket socket) throws IOException {
 client = socket;
 in = new BufferedReader(new InputStreamReader(client.getInputStream(), charset));
 out = new PrintWriter(new OutputStreamWriter(client.getOutputStream(), charset));
 start();
}

代码示例来源:origin: apache/zookeeper

public static void dump(String host, int port) {
  Socket s = null;
  try {
    byte[] reqBytes = new byte[4];
    ByteBuffer req = ByteBuffer.wrap(reqBytes);
    req.putInt(ByteBuffer.wrap("dump".getBytes()).getInt());
    s = new Socket();
    s.setSoLinger(false, 10);
    s.setSoTimeout(20000);
    s.connect(new InetSocketAddress(host, port));
    InputStream is = s.getInputStream();
    OutputStream os = s.getOutputStream();
    os.write(reqBytes);
    byte[] resBytes = new byte[1024];
    int rc = is.read(resBytes);
    String retv = new String(resBytes);
    System.out.println("rc=" + rc + " retv=" + retv);
  } catch (IOException e) {
    LOG.warn("Unexpected exception", e);
  } finally {
    if (s != null) {
      try {
        s.close();
      } catch (IOException e) {
        LOG.warn("Unexpected exception", e);
      }
    }
  }
}

代码示例来源:origin: apache/ignite

/** {@inheritDoc} */
  @SuppressWarnings("InfiniteLoopStatement")
  @Override public void run() {
    OutputStream out = null;
    InputStream in = null;
    try {
      out = sock.getOutputStream();
      in = new BufferedInputStream(sock.getInputStream());
      while (true) {
        byte[] msg = readMessage(in);
        System.out.println(">>>>>>> [" + System.currentTimeMillis() + "] packet received, " +
          msg.length + " bytes");
        System.out.println(">>>>>>> [" + System.currentTimeMillis() + "] sending response, " +
          msg.length + " bytes");
        writeMessage(out, msg);
      }
    }
    catch (Exception e) {
      System.out.println("Finishing client thread: " + e.getMessage());
    }
    finally {
      U.closeQuiet(in);
      U.closeQuiet(out);
      U.closeQuiet(sock);
    }
  }
}

代码示例来源:origin: redisson/redisson

final void process(Socket clnt) throws IOException {
  InputStream in = new BufferedInputStream(clnt.getInputStream());
  String cmd = readLine(in);
  logging(clnt.getInetAddress().getHostName(),
      new Date().toString(), cmd);
  while (skipLine(in) > 0){
  }
  OutputStream out = new BufferedOutputStream(clnt.getOutputStream());
  try {
    doReply(in, out, cmd);
  }
  catch (BadHttpRequest e) {
    replyError(out, e);
  }
  out.flush();
  in.close();
  out.close();
  clnt.close();
}

代码示例来源:origin: log4j/log4j

static
 void roll() {
  try {
   Socket socket = new Socket(host, port);
   DataOutputStream dos = new DataOutputStream(socket.getOutputStream());
   DataInputStream dis = new DataInputStream(socket.getInputStream());
   dos.writeUTF(ExternallyRolledFileAppender.ROLL_OVER);
   String rc = dis.readUTF();
   if(ExternallyRolledFileAppender.OK.equals(rc)) {
  cat.info("Roll over signal acknowledged by remote appender.");
   } else {
  cat.warn("Unexpected return code "+rc+" from remote entity.");
  System.exit(2);
   }
  } catch(IOException e) {
   cat.error("Could not send roll signal on host "+host+" port "+port+" .",
    e);
   System.exit(2);
  }
  System.exit(0);
 }
}

相关文章